@zergai/ztc 0.26.6-dev.202611240947 → 0.27.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) hide show
  1. package/README.md +629 -167
  2. package/RUST_THIRD_PARTY_LICENSES.txt +5 -5
  3. package/bin/zmux-darwin-arm64 +0 -0
  4. package/bin/zmux-linux-x64 +0 -0
  5. package/bin/ztc-audio-darwin-arm64 +0 -0
  6. package/bin/ztc-capture-darwin-arm64 +0 -0
  7. package/bin/ztc-computer-darwin-arm64 +0 -0
  8. package/bin/ztc-llm-darwin-arm64 +0 -0
  9. package/bin/ztc-tts-darwin-arm64 +0 -0
  10. package/bin/ztc-tui-darwin-arm64 +0 -0
  11. package/bin/ztc-tui-linux-x64 +0 -0
  12. package/bin/zterm-darwin-arm64 +2 -2
  13. package/dist/App.js +6 -1
  14. package/dist/agent/agent.d.ts +21 -15
  15. package/dist/agent/agent.js +389 -163
  16. package/dist/agent/backends/codex_app_server.d.ts +7 -1
  17. package/dist/agent/backends/codex_app_server.js +11 -1
  18. package/dist/agent/backends/gemini.js +22 -8
  19. package/dist/agent/commands/batch.js +8 -0
  20. package/dist/agent/commands/config.js +10 -0
  21. package/dist/agent/commands/environment.js +5 -5
  22. package/dist/agent/commands/goal.d.ts +1 -0
  23. package/dist/agent/commands/goal.js +2 -1
  24. package/dist/agent/commands/index.js +2 -1
  25. package/dist/agent/commands/manifest.js +4 -0
  26. package/dist/agent/commands/optimize.js +5 -2
  27. package/dist/agent/commands/pane_cli.d.ts +29 -0
  28. package/dist/agent/commands/pane_cli.js +303 -0
  29. package/dist/agent/commands/settings.js +13 -3
  30. package/dist/agent/commands/shannon.js +8 -0
  31. package/dist/agent/commands/update.js +15 -3
  32. package/dist/agent/commands/zerg.js +31 -1
  33. package/dist/agent/commands/ztc_pane.js +3 -1
  34. package/dist/agent/factory.d.ts +4 -0
  35. package/dist/agent/factory.js +11 -1
  36. package/dist/agent/loop_policy.d.ts +42 -5
  37. package/dist/agent/loop_policy.js +206 -3
  38. package/dist/agent/runtime/command_jobs.d.ts +5 -0
  39. package/dist/agent/runtime/command_jobs.js +241 -31
  40. package/dist/agent/runtime/command_wait.d.ts +2 -0
  41. package/dist/agent/runtime/command_wait.js +1 -0
  42. package/dist/agent/runtime/done_report.d.ts +18 -0
  43. package/dist/agent/runtime/done_report.js +130 -0
  44. package/dist/agent/runtime/execution_context.js +4 -1
  45. package/dist/agent/runtime/failure_cause.d.ts +2 -0
  46. package/dist/agent/runtime/failure_cause.js +35 -0
  47. package/dist/agent/runtime/policy.d.ts +14 -2
  48. package/dist/agent/runtime/policy.js +104 -12
  49. package/dist/agent/runtime/quiet_job.d.ts +18 -0
  50. package/dist/agent/runtime/quiet_job.js +48 -0
  51. package/dist/agent/runtime/recovery.d.ts +1 -5
  52. package/dist/agent/runtime/recovery.js +2 -44
  53. package/dist/agent/runtime/tool_runtime.d.ts +1 -0
  54. package/dist/agent/runtime/tool_runtime.js +2 -0
  55. package/dist/agent/subagent.js +6 -1
  56. package/dist/agent/tools/deferred.js +1 -0
  57. package/dist/agent/tools/index.d.ts +2 -0
  58. package/dist/agent/tools/index.js +1 -0
  59. package/dist/agent/tools/outcome.d.ts +15 -0
  60. package/dist/agent/tools/outcome.js +107 -0
  61. package/dist/agent/tools/pane.d.ts +2 -1
  62. package/dist/agent/tools/pane.js +21 -3
  63. package/dist/agent/tools/registry.js +2 -0
  64. package/dist/agent/tools/shell.d.ts +1 -0
  65. package/dist/agent/tools/shell.js +128 -17
  66. package/dist/agent/tools/sim_domain_tools.js +4 -2
  67. package/dist/agent/tools/supervision.js +4 -2
  68. package/dist/agent/tools/types.d.ts +3 -0
  69. package/dist/app/command_context.js +5 -9
  70. package/dist/app/conversation_compaction.d.ts +4 -2
  71. package/dist/app/conversation_compaction.js +16 -5
  72. package/dist/app/headless_shell_mode.d.ts +14 -0
  73. package/dist/app/headless_shell_mode.js +7 -0
  74. package/dist/app/hosted_resident.d.ts +356 -0
  75. package/dist/app/hosted_resident.js +677 -0
  76. package/dist/app/restart.js +11 -2
  77. package/dist/app/session_manager.d.ts +5 -0
  78. package/dist/app/session_manager.js +21 -6
  79. package/dist/app/session_messages.js +6 -6
  80. package/dist/app/workspace_layout_controller.js +7 -0
  81. package/dist/batch/worktree.d.ts +10 -0
  82. package/dist/batch/worktree.js +15 -0
  83. package/dist/bench/registry.js +4 -2
  84. package/dist/cli_args.js +1 -1
  85. package/dist/cli_main.js +80 -10
  86. package/dist/cli_ratatui.d.ts +75 -0
  87. package/dist/cli_ratatui.js +485 -84
  88. package/dist/components/InputArea.js +4 -4
  89. package/dist/config/execution.d.ts +10 -0
  90. package/dist/config/execution.js +10 -0
  91. package/dist/config/hosted_runtime.d.ts +4 -1
  92. package/dist/config/hosted_runtime.js +4 -1
  93. package/dist/config/permission_pin.d.ts +34 -2
  94. package/dist/config/permission_pin.js +52 -2
  95. package/dist/config/person_command_policy.d.ts +38 -0
  96. package/dist/config/person_command_policy.js +11 -0
  97. package/dist/config/profiles.d.ts +21 -0
  98. package/dist/config/profiles.js +56 -2
  99. package/dist/config/types.d.ts +4 -1
  100. package/dist/config.js +34 -19
  101. package/dist/desktop/daily/codex_exec_adapter.js +7 -2
  102. package/dist/desktop/daily/desktop_wiring.d.ts +7 -1
  103. package/dist/desktop/daily/desktop_wiring.js +11 -3
  104. package/dist/desktop/daily/recipes.js +20 -4
  105. package/dist/desktop/health.d.ts +24 -0
  106. package/dist/desktop/health.js +151 -0
  107. package/dist/desktop/native_dialogs.d.ts +37 -0
  108. package/dist/desktop/native_dialogs.js +105 -0
  109. package/dist/diagnostics/session_export.d.ts +1 -0
  110. package/dist/diagnostics/session_export.js +28 -0
  111. package/dist/embedded/registry.js +4 -2
  112. package/dist/emulation/tool_adapters.js +9 -4
  113. package/dist/emulation/ztc_addendum.js +3 -0
  114. package/dist/headless.d.ts +11 -4
  115. package/dist/headless.js +99 -34
  116. package/dist/headless_approval.d.ts +6 -0
  117. package/dist/headless_cli.js +1 -1
  118. package/dist/hooks/runner.js +7 -6
  119. package/dist/library.d.ts +4 -0
  120. package/dist/library.js +3 -0
  121. package/dist/mcp/client.js +3 -3
  122. package/dist/modes/registry.js +13 -4
  123. package/dist/onboarding/setup_environment.js +13 -1
  124. package/dist/optimize/adapters/kernelbench.js +88 -10
  125. package/dist/optimize/adapters/types.d.ts +5 -0
  126. package/dist/optimize/executor.js +21 -0
  127. package/dist/panes/cli_install.d.ts +54 -0
  128. package/dist/panes/cli_install.js +157 -0
  129. package/dist/panes/model_catalog.js +3 -0
  130. package/dist/panes/new_pane_choices.d.ts +6 -2
  131. package/dist/panes/new_pane_choices.js +24 -12
  132. package/dist/panes/pane_cli_launch.d.ts +50 -0
  133. package/dist/panes/pane_cli_launch.js +124 -0
  134. package/dist/panes/pane_clis.d.ts +171 -0
  135. package/dist/panes/pane_clis.js +325 -0
  136. package/dist/panes/person_only_panes.d.ts +45 -0
  137. package/dist/panes/person_only_panes.js +117 -0
  138. package/dist/plugin/simulation_living.js +0 -2
  139. package/dist/plugin/simulation_living_engine.d.ts +1 -0
  140. package/dist/plugin/simulation_living_engine.js +1 -0
  141. package/dist/plugin/simulation_living_labels.d.ts +3 -0
  142. package/dist/plugin/simulation_living_labels.js +2 -0
  143. package/dist/router_auth.js +12 -1
  144. package/dist/session.js +26 -1
  145. package/dist/simulation/art/gemini_image.js +11 -5
  146. package/dist/simulation/domains/loader.js +25 -3
  147. package/dist/simulation/living/cold.d.ts +23 -0
  148. package/dist/simulation/living/cold.js +41 -0
  149. package/dist/simulation/living/context.d.ts +591 -1283
  150. package/dist/simulation/living/context.js +378 -244
  151. package/dist/simulation/living/contradictions.d.ts +14 -0
  152. package/dist/simulation/living/contradictions.js +282 -0
  153. package/dist/simulation/living/core/ids.d.ts +53 -0
  154. package/dist/simulation/living/core/ids.js +39 -0
  155. package/dist/simulation/living/core/kind.d.ts +20 -0
  156. package/dist/simulation/living/core/kind.js +15 -0
  157. package/dist/simulation/living/core/laws.d.ts +179 -0
  158. package/dist/simulation/living/core/laws.js +184 -0
  159. package/dist/simulation/living/core/ops.d.ts +257 -0
  160. package/dist/simulation/living/core/ops.js +34 -0
  161. package/dist/simulation/living/definer.d.ts +17 -1
  162. package/dist/simulation/living/definer.js +130 -51
  163. package/dist/simulation/living/definition.d.ts +174 -65
  164. package/dist/simulation/living/definition.js +287 -180
  165. package/dist/simulation/living/director.d.ts +80 -0
  166. package/dist/simulation/living/director.js +363 -0
  167. package/dist/simulation/living/frame.d.ts +108 -21
  168. package/dist/simulation/living/frame.js +111 -66
  169. package/dist/simulation/living/identifiers.d.ts +0 -1
  170. package/dist/simulation/living/identifiers.js +0 -3
  171. package/dist/simulation/living/index.d.ts +18 -9
  172. package/dist/simulation/living/index.js +18 -9
  173. package/dist/simulation/living/inference.d.ts +92 -50
  174. package/dist/simulation/living/inference.js +319 -175
  175. package/dist/simulation/living/knowledge.d.ts +28 -0
  176. package/dist/simulation/living/knowledge.js +73 -0
  177. package/dist/simulation/living/library.json +1177 -0
  178. package/dist/simulation/living/mechanics.d.ts +31 -34
  179. package/dist/simulation/living/mechanics.js +222 -138
  180. package/dist/simulation/living/model-input.d.ts +6 -3
  181. package/dist/simulation/living/model-input.js +18 -26
  182. package/dist/simulation/living/open-world.d.ts +74 -94
  183. package/dist/simulation/living/open-world.js +151 -30
  184. package/dist/simulation/living/phrases.d.ts +3 -0
  185. package/dist/simulation/living/phrases.js +37 -0
  186. package/dist/simulation/living/phrases.json +560 -0
  187. package/dist/simulation/living/projection.d.ts +316 -2
  188. package/dist/simulation/living/projection.js +50 -2
  189. package/dist/simulation/living/prompts/example-spec.json +11 -0
  190. package/dist/simulation/living/prompts/role-text.json +14 -0
  191. package/dist/simulation/living/prompts.d.ts +5 -0
  192. package/dist/simulation/living/prompts.js +275 -0
  193. package/dist/simulation/living/recall.d.ts +2 -2
  194. package/dist/simulation/living/reduce.d.ts +51 -14
  195. package/dist/simulation/living/reduce.js +941 -579
  196. package/dist/simulation/living/replay.d.ts +5 -4
  197. package/dist/simulation/living/replay.js +10 -9
  198. package/dist/simulation/living/runtime.d.ts +135 -25
  199. package/dist/simulation/living/runtime.js +1641 -583
  200. package/dist/simulation/living/scale.d.ts +96 -0
  201. package/dist/simulation/living/scale.js +124 -0
  202. package/dist/simulation/living/script.d.ts +5 -0
  203. package/dist/simulation/living/script.js +115 -0
  204. package/dist/simulation/living/shared-kinds.d.ts +4 -11
  205. package/dist/simulation/living/shared-kinds.js +11 -81
  206. package/dist/simulation/living/space.d.ts +14 -0
  207. package/dist/simulation/living/space.js +132 -0
  208. package/dist/simulation/living/state.d.ts +100 -0
  209. package/dist/simulation/living/state.js +393 -0
  210. package/dist/simulation/living/types.d.ts +829 -512
  211. package/dist/simulation/living/types.js +162 -187
  212. package/dist/simulation/living/world-rules.d.ts +100 -0
  213. package/dist/simulation/living/world-rules.js +267 -0
  214. package/dist/simulation/plugins/loader.js +11 -0
  215. package/dist/skills/loader.js +4 -0
  216. package/dist/tools.d.ts +1 -0
  217. package/dist/tools.js +1 -0
  218. package/dist/ui/ratatui/headless_pane_manager.d.ts +4 -1
  219. package/dist/ui/ratatui/headless_pane_manager.js +13 -9
  220. package/dist/ui/ratatui/pane_relay.js +29 -0
  221. package/dist/ui/ratatui/pane_type.d.ts +10 -0
  222. package/dist/ui/ratatui/pane_type.js +11 -0
  223. package/dist/ui/ratatui/process.d.ts +30 -0
  224. package/dist/ui/ratatui/process.js +133 -19
  225. package/dist/ui/ratatui/protocol.d.ts +124 -2
  226. package/dist/ui/ratatui/protocol.js +35 -0
  227. package/dist/ui/ratatui/relay_policy.js +3 -0
  228. package/dist/ui/ratatui/ztc_launch_trust.d.ts +2 -1
  229. package/dist/ui/ratatui/ztc_launch_trust.js +8 -1
  230. package/dist/ui/terminal_image.d.ts +12 -0
  231. package/dist/ui/terminal_image.js +21 -1
  232. package/dist/utils/codex_project_trust.d.ts +19 -0
  233. package/dist/utils/codex_project_trust.js +37 -0
  234. package/dist/utils/compaction.js +103 -20
  235. package/dist/utils/git_program_files.d.ts +19 -12
  236. package/dist/utils/git_program_files.js +411 -83
  237. package/dist/utils/host_shell.d.ts +10 -1
  238. package/dist/utils/host_shell.js +14 -1
  239. package/dist/utils/mid_turn_compaction.d.ts +2 -0
  240. package/dist/utils/mid_turn_compaction.js +2 -0
  241. package/dist/utils/models.js +6 -1
  242. package/dist/utils/sandbox.d.ts +109 -8
  243. package/dist/utils/sandbox.js +981 -187
  244. package/dist/utils/shell.d.ts +2 -0
  245. package/dist/utils/shell.js +10 -4
  246. package/dist/utils/subprocess_env.d.ts +47 -11
  247. package/dist/utils/subprocess_env.js +107 -15
  248. package/dist/utils/system_ps.d.ts +8 -0
  249. package/dist/utils/system_ps.js +39 -7
  250. package/dist/utils/unattended_compaction.d.ts +9 -0
  251. package/dist/utils/unattended_compaction.js +13 -0
  252. package/dist/utils/ztc_own_state.d.ts +8 -5
  253. package/dist/utils/ztc_own_state.js +17 -11
  254. package/dist/web/mirror_client.js +1 -0
  255. package/dist/web/mirror_stream.d.ts +50 -6
  256. package/dist/web/mirror_stream.js +160 -15
  257. package/dist/workflows/registry.js +3 -1
  258. package/dist/workspace/controller.js +12 -0
  259. package/dist/workspace_collision.d.ts +3 -0
  260. package/dist/workspace_collision.js +14 -1
  261. package/dist/workspace_session_context.js +2 -1
  262. package/dist/zlm-embed.mjs +3823 -1970
  263. package/node_modules/@zerg/model-contracts/README.md +16 -4
  264. package/node_modules/@zerg/model-contracts/index.js +6 -1
  265. package/npm-shrinkwrap.json +1 -1
  266. package/package.json +42 -24
  267. package/packages/model-contracts/README.md +16 -4
  268. package/packages/model-contracts/index.js +6 -1
@@ -1,46 +1,59 @@
1
1
  import { assertLivingModelCall, withContextLookup, MODEL_VIEW_NOTE, contextSelectionInput } from './model-input.js';
2
- import { BOUNDED_IDENTIFIERS_ENGINE, generatedId } from './identifiers.js';
2
+ import { generatedId } from './identifiers.js';
3
3
  import { createHash } from 'node:crypto';
4
4
  import { isDeepStrictEqual } from 'node:util';
5
5
  import { z } from 'zod';
6
- import { fitSpeechInput, speechSetting, modelContextPeople, CHARACTER_MESSAGE_SYSTEM, CHARACTER_PLAN_SYSTEM, CHARACTER_REACTION_SYSTEM, GAME_MASTER_SYSTEM, NARRATOR_EPILOGUE_SYSTEM, SPEECH_IMPACT_SYSTEM, characterMessageReplyInput, characterPlanInput, characterReactionInput, clockLabel, epilogueInput, gameMasterAttemptInput, gameMasterWorldInput, earlierTimes, personLabel, } from './context.js';
7
- import { createLivingState } from './definition.js';
8
- import { SIGNAL_NOTICES, SIGNAL_SENSES, LIVING_INFERENCE_LIMITS, epilogueResponseSchema, messageReplyResponseSchema, scopedPlanResponseSchema, scopedAttemptResponseSchema, scopedReactionResponseSchema, scopedSpeechImpactResponseSchema, } from './inference.js';
6
+ import { fitSpeechInput, speechSetting, modelContextPeople, characterMessageReplyInput, characterPlanInput, characterReactionInput, clockLabel, epilogueInput, gameMasterAttemptInput, knowsPlace, openChoices, gameMasterWorldInput, earlierTimes, personLabel, } from './context.js';
7
+ import { createLivingState, parseLivingWorldDefinition } from './definition.js';
8
+ import { LIVING_INFERENCE_LIMITS, attemptResponseSchema, epilogueResponseSchema, livingAnswerTokens, messageReplyResponseSchema, planResponseSchema, reactionResponseSchema, scopedMessageReplyResponseSchema, scopedPlanResponseSchema, scopedAttemptResponseSchema, scopedReactionResponseSchema, scopedSpeechImpactResponseSchema, speechImpactResponseSchema, } from './inference.js';
9
+ import { roleText, systemFor } from './prompts.js';
9
10
  import { blockedByGate, gatesAgainst, heldHere, importanceFloorForEffects, normViolationsFor, signalNotice, predictionReady } from './mechanics.js';
11
+ import { cueMatches, evaluateCondition } from './core/laws.js';
10
12
  import { kindRequestSchema } from './open-world.js';
13
+ import { reviseLivingKind } from './definer.js';
14
+ import { sharedKindMap } from './shared-kinds.js';
15
+ import { checkAnswerPace, checkEntityProperties, checkKindDefinition, checkSessionReach } from './world-rules.js';
16
+ import { runDirectorJob } from './director.js';
11
17
  import { observedSummary } from './projection.js';
12
- import { applyLivingEvent, arrivalFor, clockTargetAt, countNote, countResult, nearbyFor, peopleAt, travelPath, unansweredSince, votingShut, witnessesFor, TRAVEL_MINUTES_PER_HOP } from './reduce.js';
13
- import { AVERTED_ENGINE, isNight, REMINDER_ENGINE, REMINDER_MINUTES, LONG_DAY_MINUTES, LivingWorldError, MAX_CLOCK_RATE, MAX_LINE, MAX_TEXT, MAX_ROLE, FULL_SCHEDULE_INTENT_ENGINE, MAX_SPOKEN, PROMISE_IMPORTANCE, PROMISE_LEAD_MINUTES, STALL_MINUTES, THING_MEMORY_ENGINE, THINGS_SEEN_ENGINE, WALK_OFF_ENGINE, effectSchema, endingSchema, } from './types.js';
18
+ import { BOUNDS, owedSchedule } from './state.js';
19
+ import { foreignScripts, worldScripts } from './script.js';
20
+ import { answeredAgain, answeredLine, applyLivingEvent, arrivalFor, clockTargetAt, isChoiceTurn, isDecisionKind, liveExchange, nearbyFor, peopleAt, saidAgain, travelPath, unansweredSince, witnessesFor } from './reduce.js';
21
+ import { offstageSpan, pace, REACTOR_STAKE, restActionOf, restingAt, restSpan, travelCost } from './scale.js';
22
+ import { phrase } from './phrases.js';
23
+ import { proseContradictions, unknownNames } from './contradictions.js';
24
+ import { entitiesHere, siteOf } from './space.js';
25
+ import { personKnowledgeSources } from './knowledge.js';
26
+ import { LivingWorldError, MAX_CLOCK_RATE, MAX_LINE, MAX_TEXT, MAX_ROLE, MAX_CHAIN_LINKS, MAX_SPOKEN, effectSchema, endingSchema, scheduledKindSchema, } from './types.js';
14
27
  export const MAX_DUE_ITEMS_PER_STEP = 2;
15
28
  export const MAX_DUE_ERRANDS_PER_STEP = 4;
16
29
  export const MAX_REACTORS = 2;
17
30
  // Every player command runs within this many model calls. The player's own attempt or
18
31
  // words come first; reactions, replies and due plans are skipped once the budget is spent.
19
32
  export const MAX_MODEL_CALLS_PER_COMMAND = 6;
20
- export const MAX_NONPLAYER_MINUTES_PER_COMMAND = 20;
21
33
  // From this importance up, an act is a shock: every witness decides what to do about it.
22
34
  export const SHOCK_IMPORTANCE = 7;
23
35
  const ROUTINE_PLAN_IMPORTANCE = 3;
24
- export const SHOCK_PLAN_DELAY_MINUTES = 5;
25
- export const OTHERS_MAX_MINUTES = 10;
26
- // In a live world an act longer than this only begins at once; its end is ruled when its time has passed.
27
- export const LONG_ACT_MINUTES = 10;
28
- // A deadline the Game Master cannot rule happens this long after its time, from its data alone.
29
- export const DEADLINE_GRACE_MINUTES = 15;
30
36
  // Failures that mean others' answers must wait, not that the player's act did not happen.
31
37
  const LATER_CODES = new Set(['inference-unavailable', 'inference-invalid', 'run-paused']);
32
- export const ERRAND_DELAY_MINUTES = 3;
33
- export const SPEECH_MINUTES = 1;
34
- export const MESSAGE_MINUTES = 1;
35
- export const MESSAGE_REPLY_DELAY_MINUTES = 10;
36
- export const IDLE_WAIT_MINUTES = 60;
37
- export const OVERDUE_WAIT_MINUTES = 15;
38
+ const RETRYABLE = Object.freeze({ 'inference-unavailable': true, 'run-paused': true });
38
39
  export const PLAYER_MAX_TEXT_BYTES = 2000;
39
- // A person whose decision names no next activity keeps at it this long before deciding again.
40
- export const DEFAULT_ACTIVITY_MINUTES = 30;
41
40
  const MIN_SEEN_LENGTH = 3;
42
41
  // A ruling that returns to a changed scene is ruled again at most this many times.
43
42
  const MAX_STALE_RULINGS = 2;
43
+ export const OBJECTIVE_EFFECT_KINDS = new Set([
44
+ 'entity.create', 'property.set', 'relation.set', 'move', 'take', 'drop', 'object.update', 'entity.move', 'entity.condition',
45
+ 'cell.add',
46
+ 'place.create', 'person.create', 'shift', 'hold', 'role', 'incapacitate', 'request.open',
47
+ ]);
48
+ export const EFFECT_KINDS = Object.freeze({
49
+ say: 'say', message: 'message', requestOpen: 'request.open', requestUpdate: 'request.update', stance: 'stance', normViolation: 'norm.violation',
50
+ });
51
+ export const EVENT_KINDS = Object.freeze({ message: 'message' });
52
+ export const SCHEDULE_KINDS = Object.freeze({ plan: 'plan' });
53
+ export const PLAN_OVERDUE_PACE = 'defaultActivity';
54
+ export function planOverdueAfter(calendar) {
55
+ return pace(calendar, PLAN_OVERDUE_PACE);
56
+ }
44
57
  const sha256 = (value) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
45
58
  function characterInputRefs(state, call, actorId, causeSeq = null) {
46
59
  if (call.role !== 'character' || actorId === null)
@@ -48,6 +61,7 @@ function characterInputRefs(state, call, actorId, causeSeq = null) {
48
61
  const person = state.people[actorId];
49
62
  if (!person)
50
63
  return [];
64
+ let knowledge = null;
51
65
  const memories = new Map(person.memories.map(memory => [memory.id, memory]));
52
66
  const refs = [];
53
67
  for (const field of ['memories', 'recentlySeen', 'landmarks', 'pressing']) {
@@ -110,17 +124,19 @@ function characterInputRefs(state, call, actorId, causeSeq = null) {
110
124
  evidenceEventSeq: belief.source.eventSeq });
111
125
  });
112
126
  const seen = new Set(refs.map(ref => ref.path));
113
- const add = (path, value) => {
127
+ const add = (path, value, parentId) => {
114
128
  if (seen.has(path))
115
129
  return;
116
130
  const rootEnd = path.indexOf('/', 1);
117
131
  const root = path.slice(1, rootEnd < 0 ? undefined : rootEnd);
118
132
  const record = value !== null && typeof value === 'object' && !Array.isArray(value)
119
133
  ? value : null;
134
+ const inherited = typeof record?.id === 'string' ? null : parentId;
120
135
  const rootEnd0 = path.indexOf('/', 1);
121
136
  const id = typeof record?.id === 'string' && path.slice(1, rootEnd0 < 0 ? undefined : rootEnd0) !== 'goals' ? record.id : actorId;
122
137
  let kind = 'self';
123
138
  let evidenceEventSeq = 0;
139
+ let evidenceKind = null;
124
140
  if (root === 'scene' || root === 'exits' || root === 'playerHere')
125
141
  kind = 'present';
126
142
  else if (root === 'directory')
@@ -148,11 +164,11 @@ function characterInputRefs(state, call, actorId, causeSeq = null) {
148
164
  }
149
165
  else if (root === 'duePlan')
150
166
  kind = 'schedule';
151
- const refId = root === 'scene' || root === 'exits' ? record?.id ?? person.placeId
167
+ const refId = root === 'scene' || root === 'exits' ? record?.id ?? inherited ?? person.placeId
152
168
  : root === 'playerId' || root === 'playerName' || root === 'playerPronouns' || root === 'playerHere' ? state.playerId
153
169
  : root === 'directory' && path.startsWith('/directory/places/') ? record?.id
154
170
  : root === 'happened' || root === 'message' ? String(evidenceEventSeq)
155
- : id;
171
+ : inherited ?? id;
156
172
  if (typeof refId !== 'string')
157
173
  return;
158
174
  let sourceId = refId;
@@ -179,29 +195,36 @@ function characterInputRefs(state, call, actorId, causeSeq = null) {
179
195
  if (kind === 'known-place' && refId !== person.placeId
180
196
  && !state.places[person.placeId]?.connections.includes(refId)) {
181
197
  evidenceEventSeq = person.memories.find(memory => memory.placeId === refId && memory.evidence)?.evidence?.eventSeq ?? 0;
198
+ evidenceKind = 'memory';
199
+ }
200
+ if (kind === 'known-person') {
201
+ const sources = (knowledge ??= personKnowledgeSources(state, person)).get(refId) ?? [];
202
+ const source = sources.find(item => item.eventSeq > 0) ?? sources[0];
203
+ if (source !== undefined) {
204
+ evidenceEventSeq = source.eventSeq;
205
+ evidenceKind = source.kind;
206
+ }
182
207
  }
183
- if (kind === 'known-person' && state.people[refId]?.placeId !== person.placeId) {
184
- evidenceEventSeq = person.memories.find(memory => memory.participantIds.includes(refId) && memory.evidence)?.evidence?.eventSeq
185
- ?? person.beliefs.find(belief => belief.source.personId === refId)?.source.eventSeq ?? 0;
186
- }
187
- refs.push({ path, inputSha256: sha256(value), kind, id: sourceId, evidenceEventSeq });
208
+ refs.push({ path, inputSha256: sha256(value), kind, id: sourceId, evidenceEventSeq, ...(evidenceKind === null ? {} : { evidenceKind }) });
188
209
  seen.add(path);
189
210
  };
190
- const visit = (value, path) => {
211
+ const visit = (value, path, parentId) => {
191
212
  if (Array.isArray(value)) {
192
- value.forEach((item, index) => visit(item, `${path}/${index}`));
213
+ value.forEach((item, index) => visit(item, `${path}/${index}`, parentId));
193
214
  return;
194
215
  }
195
- add(path, value);
196
- if (value !== null && typeof value === 'object')
216
+ add(path, value, parentId);
217
+ if (value !== null && typeof value === 'object') {
218
+ const id = typeof value.id === 'string' ? value.id : parentId;
197
219
  for (const [key, child] of Object.entries(value)) {
198
220
  if (Array.isArray(child))
199
- visit(child, `${path}/${key.replaceAll('~', '~0').replaceAll('/', '~1')}`);
221
+ visit(child, `${path}/${key.replaceAll('~', '~0').replaceAll('/', '~1')}`, id);
200
222
  }
223
+ }
201
224
  };
202
225
  for (const [key, value] of Object.entries(call.input))
203
226
  if (key !== 'phase' && key !== 'clock')
204
- visit(value, `/${key.replaceAll('~', '~0').replaceAll('/', '~1')}`);
227
+ visit(value, `/${key.replaceAll('~', '~0').replaceAll('/', '~1')}`, null);
205
228
  return refs;
206
229
  }
207
230
  const clampInt = (value, min, max, fallback) => typeof value === 'number' && Number.isInteger(value) ? Math.max(min, Math.min(max, value)) : fallback;
@@ -215,22 +238,32 @@ class Session {
215
238
  cell;
216
239
  inference;
217
240
  takenEntityIds;
241
+ reduce;
242
+ witnesses;
243
+ nearby;
218
244
  events = [];
219
245
  audit = [];
246
+ startedAtRevision;
220
247
  calls = 0;
221
248
  nonPlayerMinutes = 0;
249
+ heldForAnswer = 0;
222
250
  // How many acts made in answer to another act are being ruled now.
223
251
  answeringActs = 0;
224
- constructor(cell, inference, takenEntityIds = async () => new Set()) {
252
+ constructor(cell, inference, takenEntityIds = async () => new Set(), reduce = applyLivingEvent, witnesses = witnessesFor, nearby = nearbyFor) {
225
253
  this.cell = cell;
226
254
  this.inference = inference;
227
255
  this.takenEntityIds = takenEntityIds;
256
+ this.reduce = reduce;
257
+ this.witnesses = witnesses;
258
+ this.nearby = nearby;
259
+ this.startedAtRevision = cell.state.revision;
228
260
  }
229
261
  get state() { return this.cell.state; }
230
262
  set state(value) { this.cell.state = value; }
231
263
  live() { return this.state.clockRate !== null; }
232
264
  draft(fields) {
233
- return { seq: this.state.revision + 1, at: this.state.clock, witnessIds: witnessesFor(this.state, fields), nearbyIds: nearbyFor(this.state, fields), ...fields };
265
+ const channel = fields.channel ?? null;
266
+ return { seq: this.state.revision + 1, at: this.state.clock, witnessIds: this.witnesses(this.state, fields), nearbyIds: this.nearby(this.state, { ...fields, channel }), channel, ...fields };
234
267
  }
235
268
  commit(fields) {
236
269
  const live = this.live();
@@ -238,44 +271,67 @@ class Session {
238
271
  if (fields.kind === 'plan' && fields.observed === undefined && fields.perceivedBy === undefined)
239
272
  fields = { ...fields, perceivedBy: [] };
240
273
  const before = this.state;
241
- this.state = applyLivingEvent(this.state, this.draft(fields));
274
+ this.state = this.reduce(this.state, this.draft(fields), this.cell.cold);
242
275
  // The record keeps the event as the world accepted it, with what reached people elsewhere.
243
276
  const event = this.state.events.at(-1);
244
277
  this.events.push(event);
245
278
  this.cell.log?.push(event);
279
+ this.cell.onCommit?.(event);
246
280
  // In a live world acts do not move the clock, so only a turn-mode command counts their minutes.
247
281
  if (!live && event.actorId !== this.state.playerId)
248
282
  this.nonPlayerMinutes += event.minutes;
249
- this.reportCounts(before, event);
250
283
  return event;
251
284
  }
252
- // A vote the player is a member of, counted out of the player's sight, reaches the player as news where they are:
253
- // the problem it settles then reads as settled to them, as it does to those who saw the count. Only the count's own
254
- // settlement is news: a problem settled before the count, or in another way by the act that made it, is not.
255
- reportCounts(before, event) {
256
- const player = this.state.people[this.state.playerId];
257
- for (const id of before.openDecisionIds ?? []) {
258
- const decision = this.state.entities[id];
259
- if (decision?.result === undefined || !decision.members?.includes(player.id) || decision.settles === undefined)
260
- continue;
261
- const tension = this.state.tensions.find(candidate => candidate.id === decision.settles);
262
- const note = countNote(decision);
263
- if (tension?.status !== 'settled' || tension.resolution !== note || tension.playerView?.status === 'settled')
264
- continue;
265
- this.commit({ kind: 'world', actorId: null, placeId: player.placeId, summary: `Word reaches ${player.name} that the votes on ${decision.name} were counted: ${decision.result}.`,
266
- narration: null, outcome: null, minutes: 0, causeSeq: event.seq, importance: 6, suggestions: [], reach: 'here', notice: null, visibleTensionIds: [tension.id],
267
- effects: [{ kind: 'tension.update', tensionId: tension.id, status: 'settled', note }] });
268
- }
285
+ answering(personId, answering) {
286
+ this.cell.onAnswering?.(personId, answering);
269
287
  }
270
288
  player() { return this.state.people[this.state.playerId]; }
271
289
  // A person decides one thing at a time across every flow on this world: a second decision waits
272
290
  // until the first is recorded, then reads the world as it is. A flow may decide again for someone it
273
291
  // already holds. The turn covers the person's own decision and its record, never others' answers
274
292
  // to it, so two people who speak to each other at once never wait on each other.
275
- async takeTurn(personId) {
293
+ async takeTurn(personId, priority = false) {
276
294
  const turns = (this.cell.turns ??= new Map());
277
- for (let held = turns.get(personId); held !== undefined && held.session !== this; held = turns.get(personId))
278
- await held.done;
295
+ const gates = (this.cell.turnPriority ??= new Map());
296
+ let gate;
297
+ if (priority) {
298
+ gate = gates.get(personId);
299
+ if (gate === undefined) {
300
+ let end = () => { };
301
+ const done = new Promise(resolve => { end = resolve; });
302
+ gate = { session: this, count: 0, done, end };
303
+ gates.set(personId, gate);
304
+ }
305
+ gate.count += 1;
306
+ }
307
+ const releasePriority = () => {
308
+ if (gate === undefined)
309
+ return;
310
+ gate.count -= 1;
311
+ if (gate.count === 0) {
312
+ gates.delete(personId);
313
+ gate.end();
314
+ }
315
+ };
316
+ try {
317
+ for (;;) {
318
+ const held = turns.get(personId);
319
+ if (held !== undefined && held.session !== this) {
320
+ await held.done;
321
+ continue;
322
+ }
323
+ const waiting = priority ? undefined : gates.get(personId);
324
+ if (waiting !== undefined && waiting.session !== this) {
325
+ await waiting.done;
326
+ continue;
327
+ }
328
+ break;
329
+ }
330
+ }
331
+ catch (error) {
332
+ releasePriority();
333
+ throw error;
334
+ }
279
335
  let turn = turns.get(personId);
280
336
  if (turn === undefined) {
281
337
  let end = () => { };
@@ -295,16 +351,24 @@ class Session {
295
351
  turns.delete(personId);
296
352
  mine.end();
297
353
  }
354
+ releasePriority();
298
355
  };
299
356
  }
300
- canSpend() { return this.calls < MAX_MODEL_CALLS_PER_COMMAND && this.nonPlayerMinutes < MAX_NONPLAYER_MINUTES_PER_COMMAND; }
301
- canSpendOptional() {
357
+ canSpend() { return this.calls < MAX_MODEL_CALLS_PER_COMMAND && this.nonPlayerMinutes < pace(this.state.calendar, 'nonPlayerBudget'); }
358
+ canSpendOptional(answering = false) {
302
359
  if (!this.canSpend())
303
360
  return false;
304
- const due = this.state.schedule.some(item => item.at <= this.state.clock
305
- && (item.kind === 'world' || item.kind === 'plan' || item.kind === 'reply' || item.kind === 'finish')
306
- && (item.personId === null || (!this.state.people[item.personId]?.incapacitated && !this.state.people[item.personId]?.isPlayer)));
307
- return !due || this.calls < MAX_MODEL_CALLS_PER_COMMAND - MAX_DUE_ITEMS_PER_STEP;
361
+ let due = false;
362
+ for (const item of this.state.schedule) {
363
+ if (item.at > this.state.clock)
364
+ break;
365
+ if ((item.kind === 'world' || item.kind === 'plan' || item.kind === 'reply' || item.kind === 'answer' || item.kind === 'finish')
366
+ && (item.personId === null || (!this.state.people[item.personId]?.incapacitated && !this.state.people[item.personId]?.isPlayer))) {
367
+ due = true;
368
+ break;
369
+ }
370
+ }
371
+ return !due || this.calls + (answering ? 0 : this.heldForAnswer) < MAX_MODEL_CALLS_PER_COMMAND - MAX_DUE_ITEMS_PER_STEP;
308
372
  }
309
373
  // With build, a host that makes the call wait may build it again from the world as it is when it goes.
310
374
  async complete(call, actorId, causeSeq = null, build, wanted = () => true, lookup = true) {
@@ -312,18 +376,16 @@ class Session {
312
376
  throw new LivingWorldError('run-paused', 'The world is paused');
313
377
  if (!this.canSpend())
314
378
  throw new LivingWorldError('inference-unavailable', 'The world-turn budget is exhausted');
315
- const originalSystem = call.system;
316
- const selecting = lookup && build !== undefined && call.input.view === MODEL_VIEW_NOTE;
379
+ const selecting = lookup && build !== undefined && call.input.view === MODEL_VIEW_NOTE && this.calls + 2 <= MAX_MODEL_CALLS_PER_COMMAND;
317
380
  if (selecting) {
318
- if (this.calls + 2 > MAX_MODEL_CALLS_PER_COMMAND)
319
- throw new LivingWorldError('inference-unavailable', 'The world-turn budget cannot fit context selection and a decision');
320
381
  call = { ...call, responseSchema: withContextLookup(call.responseSchema, call.input), input: contextSelectionInput(call.input),
321
- system: 'Select context for the next decision. The input shows only part of the world. Read the current action, speech, message or plan. If it names a needed person whose ID is absent from the shown cards, request that exact name or ID in contextRequest. Never substitute someone else or infer that an omitted person is absent. Request at most two identities. Use an empty array when the shown people suffice. Do not decide or narrate the action yet.',
382
+ system: roleText('context-selection'),
322
383
  };
323
384
  }
385
+ call = { ...call, maxTokens: Math.max(call.maxTokens, livingAnswerTokens(call.responseSchema)) };
324
386
  assertLivingModelCall(call);
325
387
  const startedAt = performance.now();
326
- let sent = { input: call.input, responseSchema: call.responseSchema, revision: this.state.revision, inputRefs: characterInputRefs(this.state, call, actorId, causeSeq) };
388
+ let sent = { input: call.input, responseSchema: call.responseSchema, system: call.system, revision: this.state.revision, maxTokens: call.maxTokens, inputRefs: characterInputRefs(this.state, call, actorId, causeSeq) };
327
389
  let builtFrom = this.state;
328
390
  // Built again only when the world has changed since.
329
391
  const rebuild = build === undefined ? undefined : () => {
@@ -333,9 +395,11 @@ class Session {
333
395
  if (selecting) {
334
396
  next.responseSchema = call.responseSchema;
335
397
  next.input = contextSelectionInput(next.input);
398
+ next.system = call.system;
336
399
  }
337
- assertLivingModelCall({ ...call, ...next });
338
- sent = { ...next, revision: this.state.revision, inputRefs: characterInputRefs(this.state, { ...call, ...next }, actorId, causeSeq) };
400
+ const fitted = { ...next, maxTokens: Math.max(call.maxTokens, livingAnswerTokens(next.responseSchema)) };
401
+ assertLivingModelCall({ ...call, ...fitted });
402
+ sent = { ...fitted, revision: this.state.revision, inputRefs: characterInputRefs(this.state, { ...call, ...fitted }, actorId, causeSeq) };
339
403
  }
340
404
  return sent;
341
405
  };
@@ -358,7 +422,7 @@ class Session {
358
422
  }
359
423
  this.audit.push({ phase: call.phase, role: call.role, actorId, status: 'accepted', failureCode: null, inputSha256: sha256(sent.input), outputSha256: sha256(answer), latencyMs: Math.round(performance.now() - startedAt) });
360
424
  // A queued rebuild can need selection for the first time. Discard that proposal before any effects.
361
- if (!selecting && lookup && build && sent.input.view === MODEL_VIEW_NOTE) {
425
+ if (!selecting && lookup && build && sent.input.view === MODEL_VIEW_NOTE && this.canSpend()) {
362
426
  return await this.complete({ ...call, ...build() }, actorId, causeSeq, build, wanted);
363
427
  }
364
428
  const requested = answer !== null && typeof answer === 'object' ? answer.contextRequest : undefined;
@@ -372,39 +436,68 @@ class Session {
372
436
  const next = build(focusIds);
373
437
  return { ...next, input: { ...next.input, ...(unavailable.length === 0 ? {} : { contextLookup: { unavailable } }) } };
374
438
  };
375
- return await this.complete({ ...call, system: originalSystem, ...focused() }, actorId, causeSeq, focused, wanted, false);
439
+ return await this.complete({ ...call, ...focused() }, actorId, causeSeq, focused, wanted, false);
376
440
  }
377
441
  return answer;
378
442
  }
379
- rejectLast(reason) {
443
+ rejectLast(reason, reasons = []) {
380
444
  const last = this.audit.at(-1);
381
445
  if (last) {
382
446
  last.status = 'rejected';
383
447
  last.failureCode = reason;
448
+ if (reasons.length > 0)
449
+ last.reasons = [...reasons];
384
450
  }
385
451
  }
452
+ noteLast(reasons) {
453
+ const last = this.audit.at(-1);
454
+ if (last && reasons.length > 0)
455
+ last.reasons = [...(last.reasons ?? []), ...reasons];
456
+ }
386
457
  step() { return { state: this.state, events: this.events, audit: this.audit, modelCalls: this.calls }; }
387
458
  }
388
459
  const quiet = { reach: 'here', notice: null };
389
- // Time away for home, sleep or an errand: a quarter hour to a day.
390
- const AWAY_MINUTES = { min: 15, max: 1440 };
391
- // Someone who goes home at night, or after a long day up, stays at least the night; by day, at least
392
- // two hours, so no one goes home every half hour and no one leaves at four for the whole evening.
393
- const GO_HOME_MINUTES = 480;
394
- const DAY_AWAY_MINUTES = 120;
460
+ const instant = { minutes: 0 };
395
461
  const NO_MODEL = { complete: async () => { throw new LivingWorldError('inference-unavailable', 'This step needs no model'); } };
462
+ export function validateLivingWorldDefinition(value) {
463
+ const definition = parseLivingWorldDefinition(value);
464
+ checkAnswerPace(definition);
465
+ if (definition.calendar !== undefined)
466
+ checkSessionReach({ ...definition, sharedKinds: sharedKindMap() });
467
+ startLivingWorld(definition, 'start-check', Date.UTC(2026, 0, 1));
468
+ return definition;
469
+ }
396
470
  // A live world starts on the server clock at nowMs; a world without a clock rate moves with its events.
397
471
  export function startLivingWorld(definition, seed, nowMs) {
398
472
  const initial = createLivingState(definition, seed);
399
- const session = new Session({ state: initial }, NO_MODEL);
473
+ const session = new Session({ state: initial }, NO_MODEL, undefined, applyLivingEvent, witnessesFor, nearbyFor);
474
+ const kinds = definition.kinds ?? [];
475
+ const channels = definition.channels ?? [];
476
+ const places = definition.places ?? [];
477
+ const cast = definition.cast ?? [];
478
+ const entities = definition.entities ?? [];
479
+ const objects = definition.objects ?? [];
480
+ const kindIds = new Set([...Object.keys(sharedKindMap()), ...kinds.map(kind => kind.id)]);
481
+ const channelIds = new Set(channels.map(channel => channel.id));
482
+ kinds.forEach((kind, index) => checkKindDefinition(kind, kindIds, channelIds, `kinds[${index}]`, 'effect-invalid'));
483
+ const placeIds = new Set(places.map(place => place.id));
484
+ const peopleIds = new Set([definition.player.id, ...cast.map(person => person.id)]);
485
+ const entityIds = new Set(entities.map(entity => entity.id));
486
+ const objectIds = new Set(objects.map(object => object.id));
487
+ const entityKinds = new Map(entities.map(entity => [entity.id, entity.kindId]));
488
+ entities.forEach((entity, index) => {
489
+ const kind = kinds.find(candidate => candidate.id === entity.kindId) ?? sharedKindMap()[entity.kindId];
490
+ if (kind !== undefined) {
491
+ checkEntityProperties(entity, kind, `entities[${index}]`, { placeIds, peopleIds, entityIds, objectIds, entityKinds, tensionId: definition.tension.id }, 'effect-invalid');
492
+ }
493
+ });
400
494
  const authoredEffects = [
401
- ...definition.kinds.map(kind => ({ kind: 'kind.define', definition: kind })),
402
- ...definition.entities.map(entity => ({ kind: 'entity.create', entityId: entity.id, kindId: entity.kindId, name: entity.name, placeId: entity.placeId,
403
- ...(entity.members ? { memberIds: entity.members } : {}), ...(entity.settles ? { settles: entity.settles } : {}), ...(entity.transfers ? { transfers: entity.transfers } : {}),
495
+ ...kinds.map(kind => ({ kind: 'kind.define', definition: kind })),
496
+ ...entities.map(entity => ({ kind: 'entity.create', entityId: entity.id, kindId: entity.kindId, name: entity.name, containerId: entity.containerId,
404
497
  ...(entity.knownTo ? { knownTo: entity.knownTo } : {}), ...(entity.hidden ? { hidden: true } : {}) })),
405
498
  // A paper is sealed after its words are written, whatever order its world lists them in.
406
- ...definition.entities.flatMap(entity => Object.entries(entity.properties).sort(([left], [right]) => Number(left === 'sealed') - Number(right === 'sealed')).map(([propertyId, value]) => ({ kind: 'property.set', entityId: entity.id, propertyId, value }))),
407
- ...definition.entities.flatMap(entity => Object.entries(entity.relations).map(([relationId, targetId]) => ({ kind: 'relation.set', entityId: entity.id, relationId, targetId }))),
499
+ ...entities.flatMap(entity => Object.entries(entity.properties).sort(([left], [right]) => Number(left === 'sealed') - Number(right === 'sealed')).map(([propertyId, value]) => ({ kind: 'property.set', entityId: entity.id, propertyId, value }))),
500
+ ...entities.flatMap(entity => Object.entries(entity.relations).map(([relationId, targetId]) => ({ kind: 'relation.set', entityId: entity.id, relationId, targetId }))),
408
501
  ];
409
502
  session.commit({
410
503
  kind: 'opening', actorId: null, placeId: initial.people[initial.playerId].placeId, summary: initial.opening.title, narration: initial.opening.situation,
@@ -417,10 +510,10 @@ export function startLivingWorld(definition, seed, nowMs) {
417
510
  }
418
511
  return session.step();
419
512
  }
420
- function clockFields(paused, rate, nowMs) {
513
+ function clockFields(paused, rate, nowMs, hold = false) {
421
514
  return {
422
- kind: 'clock', actorId: null, placeId: null, summary: paused ? 'The world is paused.' : `The world runs at ${rate} game minutes a minute.`,
423
- narration: null, outcome: null, minutes: 0, effects: [{ kind: 'clock', paused, rate }], causeSeq: null, importance: 1, suggestions: [],
515
+ kind: 'clock', actorId: null, placeId: null, summary: paused ? phrase('clock.paused') : phrase('clock.runs'),
516
+ narration: null, outcome: null, minutes: 0, effects: [{ kind: 'clock', paused, rate, ...(hold ? { hold: true } : {}) }], causeSeq: null, importance: 1, suggestions: [],
424
517
  realAt: Math.floor(nowMs), ...quiet,
425
518
  };
426
519
  }
@@ -437,19 +530,19 @@ export function setLivingClock(options) {
437
530
  throw new LivingWorldError('run-finished', 'This story has finished');
438
531
  const rate = options.rate ?? state.clockRate;
439
532
  if (rate === null || !Number.isInteger(rate) || rate < 1 || rate > MAX_CLOCK_RATE) {
440
- throw new LivingWorldError('command-invalid', `The clock runs at 1 to ${MAX_CLOCK_RATE} game minutes a minute`);
533
+ throw new LivingWorldError('command-invalid', `The clock runs at 1 to ${MAX_CLOCK_RATE} ticks a minute`);
441
534
  }
442
535
  const paused = options.paused ?? state.paused;
443
- if (paused === state.paused && rate === state.clockRate)
536
+ if (options.hold !== true && paused === state.paused && rate === state.clockRate)
444
537
  return session.step();
445
- session.commit(clockFields(paused, rate, options.nowMs));
538
+ session.commit(clockFields(paused, rate, options.nowMs, options.hold === true));
446
539
  return session.step();
447
540
  }
448
541
  // The next moment after now that something is due; the clock never passes it unsettled.
449
542
  function nextDueAfter(state) {
450
543
  let next = null;
451
- for (const list of [state.schedule, state.meterSchedule]) {
452
- const item = list.find(candidate => candidate.at > state.clock);
544
+ for (const list of [state.schedule, state.predictions.items]) {
545
+ const item = list.find(candidate => candidate.at > state.clock && candidate.series !== 'director-check');
453
546
  if (item && (next === null || item.at < next))
454
547
  next = item.at;
455
548
  }
@@ -473,7 +566,7 @@ export function tickLivingWorld(cell, nowMs, options = {}) {
473
566
  if (to <= state.clock)
474
567
  return null;
475
568
  return new Session(cell, NO_MODEL).commit({
476
- kind: 'tick', actorId: null, placeId: null, summary: `The clock reaches ${clockLabel(to)}.`, narration: null, outcome: null,
569
+ kind: 'tick', actorId: null, placeId: null, summary: phrase('tick.clock', { clock: clockLabel(state.calendar, to) }), narration: null, outcome: null,
477
570
  minutes: to - state.clock, effects: [], causeSeq: null, importance: 1, suggestions: [], realAt, ...quiet,
478
571
  });
479
572
  }
@@ -481,27 +574,65 @@ function recoveringPeople(state) {
481
574
  return Object.values(state.people).filter(person => person.incapacitatedBy !== undefined && person.departed === undefined
482
575
  && blockedByGate(state, person.id, 'incapacitate') === null).map(person => person.id);
483
576
  }
577
+ const STEWARD_FACET_COUNT = 4;
578
+ const STEWARD_INTERVAL = 30;
579
+ function kindAtHand(state) {
580
+ const player = state.people[state.playerId];
581
+ for (const id of player ? entitiesHere(state, player.placeId) : []) {
582
+ const kindId = state.entities[id]?.kindId;
583
+ if (kindId !== undefined && state.kinds[kindId] !== undefined)
584
+ return kindId;
585
+ }
586
+ for (const entity of Object.values(state.entities))
587
+ if (state.kinds[entity.kindId] !== undefined)
588
+ return entity.kindId;
589
+ return null;
590
+ }
591
+ function stewardCandidate(state) {
592
+ const slots = new Set();
593
+ for (const kind of Object.values(state.kinds))
594
+ for (const property of kind.properties)
595
+ slots.add(property.id);
596
+ const entries = Object.entries(state.facetUse.items)
597
+ .filter(([facet, use]) => use.count >= STEWARD_FACET_COUNT && !slots.has(facet))
598
+ .sort(([, left], [, right]) => right.count - left.count || left.firstSeq - right.firstSeq);
599
+ const entry = entries[0];
600
+ if (entry === undefined)
601
+ return null;
602
+ const [facet, use] = entry;
603
+ const kindId = use.kindId !== null && state.kinds[use.kindId] !== undefined ? use.kindId : kindAtHand(state);
604
+ return kindId === null ? null : { facet, kindId };
605
+ }
484
606
  // Everything the world has to do now, most pressing first: recoveries, due items, then anyone
485
- // in a live world with nothing to do, who decides at once.
607
+ // in a live world with nothing to do, who decides at once. A plan runs until its time even when
608
+ // the world had no room for its next step.
486
609
  export function livingDueWork(state) {
487
610
  if (state.paused || state.status === 'finished')
488
611
  return [];
489
612
  const work = recoveringPeople(state).map(personId => ({ kind: 'recover', personId }));
490
613
  const due = [];
491
- for (const list of [state.schedule, state.meterSchedule])
614
+ for (const list of [state.schedule, state.predictions.items]) {
492
615
  for (const item of list) {
493
616
  if (item.at > state.clock)
494
617
  break;
618
+ if (isChoiceTurn(state, item) && state.people[item.personId ?? '']?.isPlayer)
619
+ continue;
495
620
  if (predictionReady(state, item))
496
621
  due.push(item);
497
622
  }
498
- due.sort((left, right) => right.importance - left.importance || left.at - right.at || left.id.localeCompare(right.id));
623
+ }
624
+ due.sort((left, right) => Number(right.kind === 'reply') - Number(left.kind === 'reply')
625
+ || right.importance - left.importance || left.at - right.at || left.sourceSeq - right.sourceSeq);
499
626
  work.push(...due.map((item) => ({ kind: 'due', item })));
500
627
  if (state.clockRate !== null) {
501
628
  for (const person of Object.values(state.people)) {
502
- if (!person.isPlayer && !person.incapacitated && !person.departed && !hasPlanned(state, person.id))
629
+ if (!person.isPlayer && !person.incapacitated && !person.departed && !person.incidental && !hasPlanned(state, person.id)
630
+ && (person.plan?.dueAt ?? 0) <= state.clock)
503
631
  work.push({ kind: 'decide', personId: person.id });
504
632
  }
633
+ const steward = stewardCandidate(state);
634
+ if (steward !== null && state.clock >= (state.stewardAt ?? 0) + STEWARD_INTERVAL)
635
+ work.push({ kind: 'steward', ...steward });
505
636
  }
506
637
  return work;
507
638
  }
@@ -518,19 +649,38 @@ export async function runLivingWork(options) {
518
649
  if (work.kind === 'recover') {
519
650
  const person = state.people[work.personId];
520
651
  if (person && recoveringPeople(state).includes(person.id)) {
521
- session.commit({ kind: 'world', actorId: null, placeId: person.placeId, summary: `${person.name} can act again.`, narration: null, outcome: null, minutes: 0,
652
+ session.commit({ kind: 'world', actorId: null, placeId: person.placeId, summary: `${person.name} can act again.`, narration: null, outcome: null, ...instant,
522
653
  effects: [], causeSeq: null, importance: 2, suggestions: [], ...quiet });
523
654
  }
524
655
  }
525
656
  else if (work.kind === 'decide') {
526
657
  const person = state.people[work.personId];
527
- if (person && !person.isPlayer && !person.incapacitated && !person.departed && !hasPlanned(state, person.id)) {
658
+ if (person && !person.isPlayer && !person.incapacitated && !person.departed && !person.incidental && !hasPlanned(state, person.id)) {
528
659
  settled = await carryOutPlan(session, { id: generatedId(state.engine, 'idle', [state.revision + 1, person.id]), at: state.clock, personId: person.id, kind: 'plan', intent: 'idle',
529
660
  placeId: null, targetId: null, sourceSeq: state.revision, importance: 1 }, false);
530
661
  }
531
662
  }
663
+ else if (work.kind === 'steward') {
664
+ const candidate = stewardCandidate(state);
665
+ const kind = state.kinds[work.kindId];
666
+ if (candidate !== null && candidate.facet === work.facet && candidate.kindId === work.kindId && kind !== undefined) {
667
+ const facets = Object.entries(state.facetUse.items)
668
+ .filter(([facet]) => facet === work.facet)
669
+ .map(([facet, use]) => ({ facet, count: use.count, text: use.text }));
670
+ try {
671
+ const definition = await reviseLivingKind({ kind, facets, requests: state.kindRequests, library: Object.values(state.kinds), inference: options.inference });
672
+ session.commit({ kind: 'world', actorId: null, placeId: null, summary: phrase('kind.revised', { id: definition.id, facet: work.facet }),
673
+ narration: null, outcome: null, effects: [{ kind: 'kind.revise', definition }], causeSeq: null, importance: 1, suggestions: [], ...instant, ...quiet });
674
+ }
675
+ catch (error) {
676
+ if (!(error instanceof LivingWorldError))
677
+ throw error;
678
+ settled = false;
679
+ }
680
+ }
681
+ }
532
682
  else {
533
- const due = [...state.schedule, ...state.meterSchedule].find(item => item.id === work.item.id);
683
+ const due = state.schedule.find(item => item.id === work.item.id) ?? state.predictions.items.find(item => item.id === work.item.id);
534
684
  if (due && due.at <= state.clock)
535
685
  settled = await settleItem(session, due);
536
686
  }
@@ -549,7 +699,6 @@ export function livingWorkIsRoutine(work) {
549
699
  }
550
700
  // Someone who has kept one activity for two game hours, carried on without deciding, is due a real
551
701
  // decision however far behind the world is, so no one stands in one plan for a whole day.
552
- const CARRY_ON_LIMIT_MINUTES = 120;
553
702
  function carriedOnTooLong(state, person) {
554
703
  const history = person.planHistory ?? [];
555
704
  const last = history.at(-1);
@@ -558,7 +707,7 @@ function carriedOnTooLong(state, person) {
558
707
  let since = last.at;
559
708
  for (let index = history.length - 1; index >= 0 && history[index].intent === last.intent; index -= 1)
560
709
  since = history[index].at;
561
- return state.clock - since >= CARRY_ON_LIMIT_MINUTES;
710
+ return state.clock - since >= pace(state.calendar, 'carryOnLimit');
562
711
  }
563
712
  // When a world falls behind its clock, someone with nothing pressing carries on with what they were
564
713
  // doing a while longer instead of waiting for the model, as when a decision names no activity. While
@@ -571,15 +720,22 @@ export function carryOnLivingWork(options) {
571
720
  const person = personId === null ? undefined : state.people[personId];
572
721
  const current = work.kind === 'due' ? state.schedule.some(item => item.id === work.item.id)
573
722
  : work.kind === 'decide' && personId !== null && !hasPlanned(state, personId);
723
+ if (!state.paused && state.status !== 'finished' && person?.incidental && work.kind === 'due' && work.item.kind === 'plan' && current) {
724
+ const plan = { intent: person.plan?.intent ?? phrase('plan.carryOn'), ...(person.plan?.seen ? { seen: person.plan.seen } : {}),
725
+ placeId: null, targetId: null, inMinutes: pace(state.calendar, 'defaultActivity') };
726
+ session.commit({ kind: 'plan', actorId: null, placeId: person.placeId, summary: phrase('act.carriesOn', { name: person.name, intent: plan.intent }).slice(0, 2000), narration: null, outcome: null,
727
+ ...instant, effects: planEffects(state, person.id, plan, state.revision + 1), causeSeq: work.item.sourceSeq || null, importance: 1, suggestions: [], ...quiet });
728
+ return { ...session.step(), settled: true };
729
+ }
574
730
  // Someone with a decision out is left to it; carrying them on meanwhile would overtake it.
575
731
  if (state.paused || state.status === 'finished' || !livingWorkIsRoutine(work) || !current || !person || person.isPlayer || person.incapacitated || person.departed
576
- || options.cell.turns?.has(person.id) || !options.modelDown && carriedOnTooLong(state, person)) {
732
+ || person.incidental || options.cell.turns?.has(person.id) || !options.modelDown && carriedOnTooLong(state, person)) {
577
733
  return { ...session.step(), settled: false };
578
734
  }
579
- const plan = { intent: person.plan?.intent ?? 'Carry on with the day', ...(person.plan?.seen ? { seen: person.plan.seen } : {}),
580
- placeId: null, targetId: null, inMinutes: DEFAULT_ACTIVITY_MINUTES };
581
- session.commit({ kind: 'plan', actorId: person.id, placeId: person.placeId, summary: `${person.name} carries on: ${plan.intent}`.slice(0, 2000), narration: null, outcome: null,
582
- minutes: 0, effects: planEffects(state, person.id, plan, state.revision + 1), causeSeq: null, importance: 1, suggestions: [], ...quiet });
735
+ const plan = { intent: person.plan?.intent ?? phrase('plan.carryOn'), ...(person.plan?.seen ? { seen: person.plan.seen } : {}),
736
+ placeId: null, targetId: null, inMinutes: pace(state.calendar, 'defaultActivity') };
737
+ session.commit({ kind: 'plan', actorId: person.id, placeId: person.placeId, summary: phrase('act.carriesOn', { name: person.name, intent: plan.intent }).slice(0, 2000), narration: null, outcome: null,
738
+ ...instant, effects: planEffects(state, person.id, plan, state.revision + 1), causeSeq: null, importance: 1, suggestions: [], ...quiet });
583
739
  return { ...session.step(), settled: true };
584
740
  }
585
741
  // Brings a live world up to the server clock: due work settles in order as the clock passes it.
@@ -589,7 +745,8 @@ export async function advanceLivingWorld(options) {
589
745
  const audit = [];
590
746
  let modelCalls = 0;
591
747
  const failed = new Set();
592
- const key = (work) => work.kind === 'due' ? `due:${work.item.id}` : `${work.kind}:${work.personId}`;
748
+ const key = (work) => work.kind === 'due' ? `due:${work.item.id}`
749
+ : work.kind === 'steward' ? `steward:${work.facet}:${work.kindId}` : `${work.kind}:${work.personId}`;
593
750
  for (let guard = 0; guard < 100_000; guard += 1) {
594
751
  if (options.cell.state.paused)
595
752
  break;
@@ -659,8 +816,8 @@ export async function runLivingCommand(options) {
659
816
  case 'finish':
660
817
  await finish(session);
661
818
  return session.step();
662
- case 'vote':
663
- playerVotes(session, command.decisionId, command.choice);
819
+ case 'choose':
820
+ playerChooses(session, command.entityId, command.slotId, command.option);
664
821
  break;
665
822
  }
666
823
  }
@@ -672,7 +829,7 @@ export async function runLivingCommand(options) {
672
829
  throw error;
673
830
  }
674
831
  if (!live)
675
- await settleDue(session);
832
+ await settleDue(session, command.kind === 'wait');
676
833
  return session.step();
677
834
  }
678
835
  // A defined kind joins this world once every kind it links to exists here; until then it stays requested.
@@ -686,7 +843,7 @@ function joinAvailableKinds(session, availableKinds) {
686
843
  // A stored definition that today's checks reject stays out of this world; the command goes on.
687
844
  try {
688
845
  session.commit({
689
- kind: 'world', actorId: null, placeId: null, summary: `Kind ${definition.id} becomes available.`,
846
+ kind: 'world', actorId: null, placeId: null, summary: phrase('kind.available', { id: definition.id }),
690
847
  narration: null, outcome: null, minutes: 0, effects: [{ kind: 'kind.define', definition }],
691
848
  causeSeq: null, importance: 1, suggestions: [], ...quiet,
692
849
  });
@@ -708,6 +865,60 @@ function requireText(text) {
708
865
  function presentCharacters(state, placeId, except = null) {
709
866
  return peopleAt(state, placeId).filter(id => id !== except && !state.people[id].isPlayer && !state.people[id].incapacitated);
710
867
  }
868
+ function inStoryOrder(state, ids) {
869
+ const wanted = new Set(ids);
870
+ return Object.keys(state.people).filter(id => wanted.has(id));
871
+ }
872
+ function reactorsFor(state, placeId, actorId, perceivers, named, effects) {
873
+ const here = inStoryOrder(state, presentCharacters(state, placeId, actorId)).filter(id => perceivers.includes(id) && id !== state.playerId);
874
+ const wanting = named.filter(id => here.includes(id));
875
+ const touched = new Set(uniqueIds(effects.flatMap(effect => Object.values(effect))));
876
+ const stake = (id) => {
877
+ const person = state.people[id];
878
+ let value = 0;
879
+ if (touched.has(id))
880
+ value += REACTOR_STAKE.touchesPerson;
881
+ if (Object.values(state.objects).some(object => touched.has(object.id) && (object.ownerId === id || object.containerId === id)))
882
+ value += REACTOR_STAKE.touchesThing;
883
+ if (Object.values(state.entities).some(entity => touched.has(entity.id) && entity.containerId === id))
884
+ value += REACTOR_STAKE.touchesThing;
885
+ for (const other of touched) {
886
+ if (other !== id && person.relationships[other]) {
887
+ value += REACTOR_STAKE.relatesToPerson;
888
+ break;
889
+ }
890
+ }
891
+ if (person.plan !== null && person.plan.targetId !== null && touched.has(person.plan.targetId))
892
+ value += REACTOR_STAKE.planTarget;
893
+ if (state.requests.some(request => request.status === 'open' && (request.senderId === id || request.receiverId === id)
894
+ && (request.senderId === actorId || request.receiverId === actorId || touched.has(request.senderId) || touched.has(request.receiverId))))
895
+ value += REACTOR_STAKE.openRequest;
896
+ if (state.tensions.some(tension => tension.status === 'open' && tension.participantIds.includes(id)
897
+ && tension.participantIds.some(other => other !== id && (other === actorId || touched.has(other)))))
898
+ value += REACTOR_STAKE.openTension;
899
+ const relationship = actorId === null ? undefined : person.relationships[actorId];
900
+ return [value, relationship === undefined ? 0 : Math.abs(relationship.trust) + Math.abs(relationship.warmth)];
901
+ };
902
+ const ranked = [...here].sort((left, right) => {
903
+ const [leftStake, leftRelationship] = stake(left);
904
+ const [rightStake, rightRelationship] = stake(right);
905
+ return rightStake - leftStake || rightRelationship - leftRelationship;
906
+ });
907
+ return [...new Set([...wanting, ...ranked])].slice(0, MAX_REACTORS);
908
+ }
909
+ function laterReactionEffects(state, seq, ids, intent, actorId, after) {
910
+ return ids.map(id => ({ kind: 'schedule', scheduledId: generatedId(state.engine, 'react', [seq, id]), personId: id,
911
+ ['inMinutes']: after + pace(state.calendar, 'reactionBeat'), intent, placeId: null, targetId: actorId,
912
+ scheduleKind: 'react', importance: 3 }));
913
+ }
914
+ function perceivedAct(actorName, observed) {
915
+ return observed ?? phrase('act.nearby', { name: actorName });
916
+ }
917
+ function splitReactors(session, actorId, reactorIds) {
918
+ if (actorId !== session.state.playerId)
919
+ return { now: [], later: [...reactorIds] };
920
+ return { now: reactorIds.slice(0, 1), later: reactorIds.slice(1) };
921
+ }
711
922
  // ---- Player commands -----------------------------------------------------------
712
923
  async function movePlayer(session, placeId) {
713
924
  const route = () => {
@@ -720,13 +931,13 @@ async function movePlayer(session, placeId) {
720
931
  if (player.incapacitated)
721
932
  throw new LivingWorldError('command-invalid', 'You cannot move now');
722
933
  if (player.held && heldHere(session.state, player.id))
723
- throw new LivingWorldError('command-invalid', `You cannot leave: ${player.held.reason}. Try something if you mean to get away.`);
934
+ throw new LivingWorldError('command-invalid', `You cannot leave: ${player.held.reason}. Try something if you mean to get offstage.`);
724
935
  const gate = blockedByGate(session.state, player.id, 'move');
725
936
  if (gate) {
726
937
  // The player hears what keeps them by the name they know it by, never its id.
727
938
  const entity = session.state.entities[gate];
728
939
  const known = entity && entity.knownTo.includes(player.id) ? entity.name : 'Something';
729
- throw new LivingWorldError('command-invalid', `You cannot leave: ${known} keeps you here. Try something if you mean to get away.`);
940
+ throw new LivingWorldError('command-invalid', `You cannot leave: ${known} keeps you here. Try something if you mean to get offstage.`);
730
941
  }
731
942
  return path;
732
943
  };
@@ -736,11 +947,11 @@ async function movePlayer(session, placeId) {
736
947
  const path = route();
737
948
  const player = session.player();
738
949
  // A long act still under way is left behind, and the player is told so.
739
- const leftBehind = session.state.engine >= WALK_OFF_ENGINE ? session.state.schedule.filter(item => item.kind === 'finish' && item.targetId === player.id).map(leaveOff) : [];
950
+ const leftBehind = (session.state.schedule.filter(item => item.kind === 'finish' && item.targetId === player.id).map(leaveOff));
740
951
  session.commit({
741
952
  kind: 'move', actorId: player.id, placeId: player.placeId,
742
953
  summary: `${player.name} leaves for ${session.state.places[placeId].name}`, narration: null, outcome: null,
743
- minutes: (path.length - 1) * TRAVEL_MINUTES_PER_HOP, effects: [...leftBehind, { kind: 'move', personId: player.id, placeId }],
954
+ minutes: travelCost(session.state, path), effects: [...leftBehind, { kind: 'move', personId: player.id, placeId }],
744
955
  causeSeq: null, importance: 1, suggestions: [], ...quiet,
745
956
  });
746
957
  }
@@ -748,6 +959,101 @@ async function movePlayer(session, placeId) {
748
959
  function gateAgainst(state, personId, actionKind) {
749
960
  return gatesAgainst(state, personId, actionKind)[0] ?? null;
750
961
  }
962
+ async function weighSpeech(session, player, text, present, elsewhere, exchange, thingsHere, toIds) {
963
+ const talking = new Set([...toIds, ...exchange.youLastSpokeTo, ...(exchange.lastSpokeToYou ? [exchange.lastSpokeToYou] : [])]);
964
+ const held = new Set([...Object.values(session.state.objects).filter(object => object.containerId === player.id).map(object => object.id),
965
+ ...thingsHere.filter(id => session.state.entities[id]?.containerId === player.id)]);
966
+ const build = (focusIds = []) => {
967
+ const input = fitSpeechInput(session.state, { speaker: { name: player.name, role: player.role }, words: text,
968
+ listeners: present.map(id => ({ id, name: session.state.people[id].name, role: session.state.people[id].role })),
969
+ ...(elsewhere.length === 0 ? {} : { elsewhere: elsewhere.map(id => ({ id, name: session.state.people[id].name })) }),
970
+ exchange,
971
+ ...(thingsHere.length === 0 ? {} : { things: thingsHere.map(id => ({ id, name: session.state.entities[id]?.name ?? session.state.objects[id].name })) }),
972
+ setting: speechSetting(session.state), place: session.state.places[player.placeId].name }, new Set([...focusIds, ...talking]), held);
973
+ const ids = (list) => (list ?? []).map(item => item.id);
974
+ const responseSchema = scopedSpeechImpactResponseSchema([...ids(input.listeners), ...ids(input.elsewhere)], ids(input.things));
975
+ return { input, responseSchema, system: systemFor('speech-reading', responseSchema, input, speechImpactResponseSchema) };
976
+ };
977
+ try {
978
+ const assessment = await session.complete({
979
+ role: 'game-master', phase: 'speech-impact', ...build(), ...LIVING_INFERENCE_LIMITS['speech-impact'],
980
+ }, player.id, null, build);
981
+ // A line presses on its listeners; a promise out loud is one they are owed from now on.
982
+ const pressed = assessment.pressure !== null && typeof assessment.pressure === 'object' ? assessment.pressure
983
+ : typeof assessment.pressure === 'string' ? { kind: 'demand', text: assessment.pressure, dueInMinutes: null } : null;
984
+ const pressure = pressed && typeof pressed.text === 'string' && pressed.text.trim() !== '' ? pressed.text.trim().slice(0, 200) : null;
985
+ const rawAct = assessment.act !== null && typeof assessment.act === 'object' ? assessment.act : null;
986
+ const actKinds = ['sign', 'initial', 'witness', 'approve', 'seal', 'hand'];
987
+ const actKind = typeof rawAct?.kind === 'string' && actKinds.includes(rawAct.kind) ? rawAct.kind : null;
988
+ const actEntity = typeof rawAct?.entityId === 'string' ? session.state.entities[rawAct.entityId] : undefined;
989
+ const actTarget = typeof rawAct?.targetId === 'string' && present.includes(rawAct.targetId) ? rawAct.targetId : null;
990
+ const markable = actEntity !== undefined && (session.state.kinds[actEntity.kindId]?.properties ?? []).some(property => property.type === 'series');
991
+ const act = actKind !== null && actEntity !== undefined && thingsHere.includes(actEntity.id) && (actKind === 'hand' ? actTarget !== null : markable) ? { kind: actKind, entityId: actEntity.id, targetId: actTarget } : null;
992
+ return {
993
+ importance: clampInt(assessment.importance, 1, 10, 3),
994
+ pressure,
995
+ promised: pressure !== null && pressed?.kind === 'promise' ? { text: pressure, dueInMinutes: typeof pressed.dueInMinutes === 'number' ? clampInt(pressed.dueInMinutes, 0, 100_000, 0) : null } : null,
996
+ loud: assessment.loud === true,
997
+ addressedIds: Array.isArray(assessment.addressedIds) ? assessment.addressedIds.filter((id) => typeof id === 'string') : [],
998
+ mentionedIds: Array.isArray(assessment.mentionedIds) ? assessment.mentionedIds.filter((id) => typeof id === 'string') : [],
999
+ aboutIds: Array.isArray(assessment.aboutIds) ? assessment.aboutIds.filter((id) => typeof id === 'string') : [],
1000
+ act,
1001
+ };
1002
+ }
1003
+ catch (error) {
1004
+ if (!(error instanceof LivingWorldError) || (error.code !== 'inference-invalid' && error.code !== 'inference-unavailable'))
1005
+ throw error;
1006
+ return null;
1007
+ }
1008
+ }
1009
+ function applyLateSpeechReading(session, speech, reading, player, heardBy, listeners) {
1010
+ const state = session.state;
1011
+ const here = heardBy.filter(id => isHere(state, id, speech.placeId ?? player.placeId));
1012
+ if (here.length === 0)
1013
+ return;
1014
+ const about = reading.aboutIds.filter(id => state.entities[id] !== undefined || state.objects[id] !== undefined);
1015
+ const effects = [];
1016
+ if (reading.promised) {
1017
+ for (const id of here)
1018
+ effects.push({ kind: 'commitment', commitmentId: generatedId(state.engine, 'promise', [speech.seq, id]),
1019
+ personId: player.id, toId: id, text: reading.promised.text, dueInMinutes: reading.promised.dueInMinutes });
1020
+ }
1021
+ if (reading.importance >= SHOCK_IMPORTANCE) {
1022
+ const line = speech.effects.find((effect) => effect.kind === 'say' && effect.personId === player.id)?.text ?? '';
1023
+ for (const id of here) {
1024
+ const said = state.events.some(event => event.seq > speech.seq && event.actorId === id
1025
+ && event.effects.some(effect => effect.kind === 'say'));
1026
+ const intent = listeners.includes(id)
1027
+ ? (said ? phrase('decision.beyond', { summary: observedSummary(speech, id) ?? speech.summary }) : phrase('decision.about', { summary: observedSummary(speech, id) ?? speech.summary })).slice(0, 600)
1028
+ : phrase('decision.said', { player: player.name, line }).slice(0, 600);
1029
+ effects.push(...shockPlanEffects(state, id, generatedId(state.engine, 'shock', [speech.seq, id]), intent, pace(session.state.calendar, 'shockPlanDelay'), player.id, true));
1030
+ }
1031
+ }
1032
+ if (effects.length === 0 && !reading.loud && about.length === 0 && reading.pressure === null)
1033
+ return;
1034
+ const readingText = reading.promised ? phrase('reading.promise', { text: reading.promised.text })
1035
+ : reading.pressure !== null ? phrase('reading.press', { pressure: reading.pressure })
1036
+ : phrase('reading.weigh', { summary: speech.summary });
1037
+ const late = session.commit({
1038
+ kind: 'world', actorId: null, placeId: speech.placeId, summary: readingText.slice(0, 2000), observed: readingText.slice(0, 2000), narration: null, outcome: null, minutes: 0,
1039
+ causeSeq: speech.seq, importance: reading.importance, suggestions: [], reach: reading.loud ? 'nearby' : 'here',
1040
+ notice: reading.loud ? phrase('notice.shout', { place: session.state.places[speech.placeId]?.name ?? phrase('notice.nearby') }) : null,
1041
+ effects, ...(about.length === 0 ? {} : { thingIds: about }), perceivedBy: here,
1042
+ });
1043
+ if (reading.loud)
1044
+ void reactNearby(session, { ...late, actorId: player.id, nearbyIds: nearbyFor(session.state, { ...late, reach: 'nearby' }) });
1045
+ }
1046
+ function speechActText(state, act) {
1047
+ const name = state.entities[act.entityId]?.name ?? act.entityId;
1048
+ switch (act.kind) {
1049
+ case 'sign': return phrase('speech.sign', { name });
1050
+ case 'initial': return phrase('speech.initial', { name });
1051
+ case 'witness': return phrase('speech.witness', { name });
1052
+ case 'approve': return phrase('speech.approve', { name });
1053
+ case 'seal': return phrase('speech.seal', { name });
1054
+ case 'hand': return act.targetId === null ? phrase('speech.handOver', { name }) : phrase('speech.handTo', { name, person: personLabel(state, act.targetId) });
1055
+ }
1056
+ }
751
1057
  async function playerSpeaks(session, rawText, rawToIds) {
752
1058
  const gag = gateAgainst(session.state, session.state.playerId, 'speak');
753
1059
  if (gag)
@@ -757,25 +1063,30 @@ async function playerSpeaks(session, rawText, rawToIds) {
757
1063
  const present = presentCharacters(session.state, player.placeId);
758
1064
  const toIds = [...new Set(rawToIds)];
759
1065
  for (const id of toIds)
760
- if (!present.includes(id))
761
- throw new LivingWorldError('person-absent', `${personLabel(session.state, id)} is not here`);
762
- let listeners = toIds.length > 0 ? byTurn(session.state, player.placeId, toIds).slice(0, MAX_REACTORS) : chooseListeners(session.state, present);
763
- let addressed = [...toIds];
1066
+ if (!session.state.people[id])
1067
+ throw new LivingWorldError('person-absent', `${id} is not here`);
1068
+ const absentTo = toIds.filter(id => !present.includes(id));
1069
+ const hereTo = toIds.filter(id => present.includes(id));
1070
+ let listeners = hereTo.length > 0 ? byTurn(session.state, player.placeId, hereTo).slice(0, MAX_REACTORS) : chooseListeners(session.state, present);
1071
+ let addressed = [...hereTo];
1072
+ let elsewhereAddressed = [];
764
1073
  let about = [];
765
1074
  // Things here or in the speaker's hand that the words could be about.
766
1075
  // The newest things here that the speaker knows of, as a scene lists them.
767
1076
  // From engine 49 words may also be about what the speaker knows lies elsewhere, the latest changed first.
768
1077
  // However full the room, eight are named: what the speaker holds, then the newest here, then elsewhere.
769
- const known = (session.state.entityPlaceIds[player.placeId] ?? []).filter(id => session.state.entities[id].knownTo.includes(player.id));
770
- const objectsHere = Object.values(session.state.objects).filter(object => (object.placeId === player.placeId || object.holderId === player.id)
771
- && (!object.hidden || object.holderId === player.id || object.custodyKnownTo.includes(player.id)));
772
- const thingsHere = session.state.engine < THING_MEMORY_ENGINE ? [] : [...new Set([
773
- ...known.filter(id => session.state.entities[id].holderId === player.id), ...objectsHere.filter(object => object.holderId === player.id).map(object => object.id),
1078
+ const known = entitiesHere(session.state, player.placeId).filter(id => session.state.entities[id].knownTo.includes(player.id));
1079
+ const objectsHere = Object.values(session.state.objects).filter(object => (object.containerId === player.placeId || object.containerId === player.id)
1080
+ && (!object.hidden || object.containerId === player.id || object.custodyKnownTo.includes(player.id)));
1081
+ const thingsHere = ([...new Set([
1082
+ ...known.filter(id => session.state.entities[id].containerId === player.id), ...objectsHere.filter(object => object.containerId === player.id).map(object => object.id),
774
1083
  ...[...known].reverse(), ...[...objectsHere].sort((left, right) => right.introducedAt - left.introducedAt || left.id.localeCompare(right.id)).map(object => object.id),
775
- ...(session.state.engine < THINGS_SEEN_ENGINE ? [] : knownElsewhere(session.state, player.id, player.placeId))
776
- ])].slice(0, SPEECH_THINGS).sort();
1084
+ ...((knownElsewhere(session.state, player.id, player.placeId)))
1085
+ ])].slice(0, SPEECH_THINGS).sort());
777
1086
  // People the player has seen who are elsewhere may be the ones meant; such words go to the room.
778
- const elsewhere = Object.keys(session.state.sightings).filter(id => !present.includes(id) && session.state.people[id] !== undefined
1087
+ const correspondents = new Set(session.state.messages.flatMap(message => message.fromId === player.id ? message.toIds
1088
+ : message.toIds.includes(player.id) ? [message.fromId] : []));
1089
+ const elsewhere = [...new Set([...Object.keys(session.state.sightings), ...correspondents])].filter(id => !present.includes(id) && session.state.people[id] !== undefined
779
1090
  && session.state.people[id].departed === undefined && id !== player.id).sort();
780
1091
  // Whom the player was just talking with, from the talk under way here.
781
1092
  const talk = session.state.conversations.filter(conversation => conversation.placeId === player.placeId && conversation.endedAt === null)
@@ -786,81 +1097,185 @@ async function playerSpeaks(session, rawText, rawToIds) {
786
1097
  let pressure = null;
787
1098
  let promised = null;
788
1099
  let loud = false;
1100
+ let spokenAct = null;
789
1101
  const nearbyListeners = nearbyFor(session.state, { placeId: player.placeId, reach: 'nearby', effects: [] });
790
- if (listeners.length > 0 || nearbyListeners.length > 0) {
791
- try {
792
- const talking = new Set([...toIds, ...exchange.youLastSpokeTo, ...(exchange.lastSpokeToYou ? [exchange.lastSpokeToYou] : [])]);
793
- const held = new Set([...Object.values(session.state.objects).filter(object => object.holderId === player.id).map(object => object.id),
794
- ...thingsHere.filter(id => session.state.entities[id]?.holderId === player.id)]);
795
- const build = (focusIds = []) => {
796
- const input = fitSpeechInput(session.state, { speaker: { name: player.name, role: player.role }, words: text,
797
- listeners: present.map(id => ({ id, name: session.state.people[id].name, role: session.state.people[id].role })),
798
- ...(elsewhere.length === 0 ? {} : { elsewhere: elsewhere.map(id => ({ id, name: session.state.people[id].name })) }),
799
- exchange,
800
- ...(thingsHere.length === 0 ? {} : { things: thingsHere.map(id => ({ id, name: session.state.entities[id]?.name ?? session.state.objects[id].name })) }),
801
- setting: speechSetting(session.state), place: session.state.places[player.placeId].name }, new Set([...focusIds, ...talking]), held);
802
- const ids = (list) => (list ?? []).map(item => item.id);
803
- return { input, responseSchema: scopedSpeechImpactResponseSchema([...ids(input.listeners), ...ids(input.elsewhere)], ids(input.things)) };
804
- };
805
- const assessment = await session.complete({
806
- role: 'game-master', phase: 'speech-impact', system: SPEECH_IMPACT_SYSTEM, ...build(), ...LIVING_INFERENCE_LIMITS['speech-impact'],
807
- }, player.id, null, build);
808
- importance = clampInt(assessment.importance, 1, 10, 3);
809
- // A line presses on its listeners; a promise out loud is one they are owed from now on.
810
- const pressed = assessment.pressure !== null && typeof assessment.pressure === 'object' ? assessment.pressure
811
- : typeof assessment.pressure === 'string' ? { kind: 'demand', text: assessment.pressure, dueInMinutes: null } : null;
812
- pressure = pressed && typeof pressed.text === 'string' && pressed.text.trim() !== '' ? pressed.text.trim().slice(0, 200) : null;
813
- if (pressure !== null && pressed?.kind === 'promise')
814
- promised = { text: pressure, dueInMinutes: typeof pressed.dueInMinutes === 'number' ? clampInt(pressed.dueInMinutes, 0, 100_000, 0) : null };
815
- loud ||= assessment.loud === true;
816
- // Words said to the room but meant for someone here by name go to them; words for someone elsewhere go to the room.
817
- const named = Array.isArray(assessment.addressedIds) ? [...new Set(assessment.addressedIds.filter((id) => typeof id === 'string' && present.includes(id)))] : [];
818
- if (toIds.length === 0 && named.length > 0) {
819
- addressed = named;
820
- listeners = byTurn(session.state, player.placeId, named).slice(0, MAX_REACTORS);
821
- }
822
- about = Array.isArray(assessment.aboutIds) ? [...new Set(assessment.aboutIds.filter((id) => typeof id === 'string' && thingsHere.includes(id)))].slice(0, 4) : [];
823
- }
824
- catch (error) {
825
- if (!(error instanceof LivingWorldError) || (error.code !== 'inference-invalid' && error.code !== 'inference-unavailable'))
826
- throw error;
827
- }
1102
+ const canWeigh = listeners.length > 0 || nearbyListeners.length > 0 || (toIds.length === 0 && elsewhere.length > 0);
1103
+ const knownAddressee = toIds.length > 0;
1104
+ let reading = null;
1105
+ let readingPromise = null;
1106
+ if (canWeigh)
1107
+ readingPromise = weighSpeech(session, player, text, present, elsewhere, exchange, thingsHere, toIds);
1108
+ if (!knownAddressee && readingPromise) {
1109
+ reading = await readingPromise;
1110
+ readingPromise = null;
1111
+ }
1112
+ else if (knownAddressee && readingPromise) {
1113
+ reading = await Promise.race([readingPromise, new Promise(resolve => setTimeout(() => resolve(null), 0))]);
1114
+ if (reading !== null)
1115
+ readingPromise = null;
1116
+ }
1117
+ if (reading) {
1118
+ importance = reading.importance;
1119
+ pressure = reading.pressure;
1120
+ promised = reading.promised;
1121
+ loud = reading.loud;
1122
+ spokenAct = reading.act;
1123
+ // Words said to the room but meant for someone here by name go to them; words for someone elsewhere go to the room.
1124
+ const named = [...new Set(reading.addressedIds.filter(id => present.includes(id)))];
1125
+ if (toIds.length === 0 && named.length > 0) {
1126
+ addressed = named;
1127
+ listeners = byTurn(session.state, player.placeId, named).slice(0, MAX_REACTORS);
1128
+ }
1129
+ if (toIds.length === 0)
1130
+ elsewhereAddressed = [...new Set(reading.addressedIds.filter(id => elsewhere.includes(id)))];
1131
+ about = [...new Set(reading.aboutIds.filter(id => thingsHere.includes(id)))].slice(0, 4);
1132
+ }
1133
+ else if (knownAddressee) {
1134
+ elsewhereAddressed = toIds.filter(id => elsewhere.includes(id));
1135
+ const papers = thingsHere.filter(id => typeof session.state.entities[id]?.properties.body?.value === 'string');
1136
+ about = [...new Set([...listeners.flatMap(id => openChoices(session.state, id).choices?.map(choice => choice.id) ?? []), ...papers])];
828
1137
  }
829
1138
  // The world went on while the words were weighed; only those still here hear them.
830
1139
  const stillHere = presentCharacters(session.state, player.placeId);
831
1140
  const heardBy = addressed.filter(id => stillHere.includes(id));
1141
+ const absent = [...new Set([...absentTo, ...elsewhereAddressed])].filter(id => !isHere(session.state, id, player.placeId)
1142
+ && !(loud && session.state.people[id].offstage === undefined && session.state.people[id].departed === undefined
1143
+ && session.state.places[player.placeId].connections.includes(session.state.people[id].placeId)));
1144
+ const noOneHears = stillHere.length === 0 && heardBy.length === 0;
832
1145
  // Anyone a serious line was said to who does not answer now has it to decide later.
833
1146
  const seq = session.state.revision + 1;
834
1147
  const leftOut = importance >= SHOCK_IMPORTANCE ? heardBy.filter(id => !listeners.includes(id)) : [];
835
- const decideLater = leftOut.flatMap(id => shockPlanEffects(session.state, id, generatedId(session.state.engine, 'shock', [seq, id]), `Decide what to do about what ${player.name} said to you: "${text}"`.slice(0, 600), SHOCK_PLAN_DELAY_MINUTES, player.id));
1148
+ const decideLater = leftOut.flatMap(id => shockPlanEffects(session.state, id, generatedId(session.state.engine, 'shock', [seq, id]), phrase('decision.said', { player: player.name, line: text }).slice(0, 600), pace(session.state.calendar, 'shockPlanDelay'), player.id));
1149
+ const forWhom = heardBy.length > 0 ? heardBy : absentTo.filter(id => session.state.people[id] !== undefined);
836
1150
  const event = session.commit({
837
1151
  kind: 'speech', actorId: player.id, placeId: player.placeId,
838
- summary: `${player.name} says to ${heardBy.length === 0 ? 'the room' : heardBy.map(id => personLabel(session.state, id)).join(' and ')}: "${text}"`.slice(0, 2000),
839
- narration: null, outcome: null, minutes: SPEECH_MINUTES,
1152
+ summary: (forWhom.length === 0 ? phrase('speech.saysRoom', { player: player.name, text }) : phrase('speech.saysTo', { player: player.name, to: forWhom.map(id => personLabel(session.state, id)).join(' and '), text })).slice(0, 2000),
1153
+ narration: null, outcome: null, minutes: noOneHears ? 0 : pace(session.state.calendar, 'speech'),
840
1154
  effects: [{ kind: 'say', personId: player.id, text, toIds: heardBy },
841
1155
  ...(promised === null ? [] : heardBy.map((id) => ({ kind: 'commitment', commitmentId: generatedId(session.state.engine, 'promise', [seq, id]), personId: player.id, toId: id,
842
1156
  text: promised.text, dueInMinutes: promised.dueInMinutes }))), ...decideLater],
843
1157
  causeSeq: null, importance, suggestions: [], ...(about.length === 0 ? {} : { thingIds: about }),
844
- reach: loud ? 'nearby' : 'here', notice: loud ? `A shout comes from ${session.state.places[player.placeId].name}.` : null,
1158
+ reach: loud ? 'nearby' : 'here', notice: loud ? phrase('notice.shout', { place: session.state.places[player.placeId].name }) : null,
845
1159
  });
846
- await react(session, listeners.filter(id => event.witnessIds.includes(id)), event, { kind: 'speech', actorId: player.id, text, narration: null, pressure }, 'reply', false);
1160
+ if (spokenAct !== null && session.canSpend())
1161
+ await adjudicate(session, player.id, speechActText(session.state, spokenAct), null, event.seq);
1162
+ if ((absent.length > 0)) {
1163
+ const line = absentAnswer(session.state, player.id, absent);
1164
+ session.commit({
1165
+ kind: 'world', actorId: null, placeId: player.placeId, summary: line, narration: null, observed: line, outcome: null, minutes: 0,
1166
+ causeSeq: event.seq, importance: 1, suggestions: [], effects: [], ...quiet,
1167
+ });
1168
+ }
1169
+ else if ((!loud) && noOneHears) {
1170
+ const names = absent.map(id => personLabel(session.state, id));
1171
+ const seen = [...new Set(absent.flatMap(id => {
1172
+ const placeId = session.state.sightings[id]?.placeId;
1173
+ return placeId === undefined ? [] : [session.state.places[placeId]?.name ?? placeId];
1174
+ }))];
1175
+ const line = names.length === 0 ? phrase('speech.noOne')
1176
+ : phrase('speech.absent', { names: names.join(' and '), verb: names.length === 1 ? 'is' : 'are', seen: seen.length === 0 ? '' : phrase('speech.absentSeen', { places: seen.join(' and ') }) });
1177
+ session.commit({
1178
+ kind: 'world', actorId: null, placeId: player.placeId, summary: line, narration: null, observed: line, outcome: null, minutes: 0,
1179
+ causeSeq: event.seq, importance: 1, suggestions: [], effects: [], ...quiet,
1180
+ });
1181
+ }
1182
+ const reactors = listeners.filter(id => event.witnessIds.includes(id));
1183
+ const trigger = { kind: 'speech', actorId: player.id, text, narration: null, pressure, thingIds: about };
1184
+ if (readingPromise)
1185
+ void readingPromise.then(late => { if (late)
1186
+ trigger.thingIds = late.aboutIds; });
1187
+ try {
1188
+ await react(session, reactors, event, trigger, 'reply', false);
1189
+ }
1190
+ catch (error) {
1191
+ if (!(error instanceof LivingWorldError) || (error.code !== 'inference-unavailable' && error.code !== 'run-paused'))
1192
+ throw error;
1193
+ if ((!session.live()))
1194
+ throw error;
1195
+ const answered = new Set(session.state.events.filter(candidate => candidate.causeSeq === event.seq)
1196
+ .flatMap(candidate => candidate.effects.flatMap(effect => effect.kind === 'say' && effect.toIds.includes(player.id) ? [effect.personId] : [])));
1197
+ const waiting = reactors.filter(id => !answered.has(id) && isHere(session.state, id, player.placeId));
1198
+ if (waiting.length > 0)
1199
+ session.commit({
1200
+ kind: 'world', actorId: null, placeId: player.placeId, summary: phrase('speech.willAnswer', { names: waiting.map(id => personLabel(session.state, id)).join(' and ') }),
1201
+ narration: null, outcome: null, minutes: 0, causeSeq: event.seq, importance: 1, suggestions: [], ...quiet, perceivedBy: [],
1202
+ effects: waiting.map((id) => ({ kind: 'schedule', scheduledId: generatedId(session.state.engine, 'answer', [event.seq, id]),
1203
+ personId: id, inMinutes: pace(session.state.calendar, 'speech'), intent: text, placeId: null, targetId: player.id, scheduleKind: 'answer', importance: 3 })),
1204
+ });
1205
+ }
1206
+ const unanswered = reactors.filter(id => !answeredLine(session.state, id, event.seq)
1207
+ && (!isHere(session.state, id, player.placeId) || session.state.people[id]?.incapacitated === true));
1208
+ if (unanswered.length > 0) {
1209
+ const line = phrase('speech.noAnswer', { names: unanswered.map(id => personLabel(session.state, id)).join(phrase('speech.and')) });
1210
+ session.commit({ kind: 'world', actorId: null, placeId: player.placeId, summary: line, narration: null, observed: line, outcome: null, ...instant,
1211
+ causeSeq: event.seq, importance: 1, suggestions: [], effects: [], ...quiet });
1212
+ }
1213
+ if (readingPromise) {
1214
+ const late = await readingPromise.catch(() => null);
1215
+ if (late) {
1216
+ applyLateSpeechReading(session, event, late, player, heardBy, listeners);
1217
+ if (late.act && session.canSpend())
1218
+ await adjudicate(session, player.id, speechActText(session.state, late.act), null, event.seq);
1219
+ }
1220
+ }
847
1221
  if (loud)
848
1222
  await reactNearby(session, event);
849
1223
  }
850
- // The player casts their own vote, seen by those present; no model reads it from their words.
851
- function playerVotes(session, decisionId, choice) {
1224
+ function absentAnswer(state, playerId, ids) {
1225
+ const here = state.people[playerId].placeId;
1226
+ return ids.map((id) => {
1227
+ const person = state.people[id];
1228
+ const sighting = state.sightings[id];
1229
+ const place = sighting === undefined ? undefined : state.places[sighting.placeId];
1230
+ const where = sighting === undefined || place === undefined ? phrase('whereabouts.unknown')
1231
+ : sighting.offstage === true ? phrase('whereabouts.left', { place: place.name, clock: clockLabel(state.calendar, sighting.at) })
1232
+ : sighting.heading === true ? phrase('whereabouts.heading', { place: place.name, clock: clockLabel(state.calendar, sighting.at) })
1233
+ : sighting.gone === true ? phrase('whereabouts.gone', { place: place.name, clock: clockLabel(state.calendar, sighting.at) })
1234
+ : phrase('whereabouts.lastSeen', { place: place.name, clock: clockLabel(state.calendar, sighting.at) });
1235
+ const options = [];
1236
+ if (sighting !== undefined && place !== undefined && sighting.offstage !== true && person.departed === undefined
1237
+ && travelPath(state, here, place.id) !== null)
1238
+ options.push(phrase('whereabouts.follow', { place: place.name }));
1239
+ if (person.departed === undefined)
1240
+ options.push(phrase('whereabouts.sendWord'));
1241
+ if (sighting !== undefined && state.places[here].connections.includes(sighting.placeId))
1242
+ options.push(phrase('whereabouts.callOut'));
1243
+ return phrase('whereabouts.line', { name: person.name, where, options: options.length === 0 ? '' : phrase('whereabouts.options', { options: options.join(', ') }) });
1244
+ }).join(' ');
1245
+ }
1246
+ function refuse(message) {
1247
+ throw new LivingWorldError('command-invalid', message);
1248
+ }
1249
+ function playerChooses(session, entityId, slotId, option) {
852
1250
  const player = session.player();
853
- const decision = session.state.entities[decisionId];
854
- if (!decision?.members?.includes(player.id))
855
- throw new LivingWorldError('command-invalid', 'You have no vote on that');
856
- const shut = votingShut(session.state, decision, session.state.clock);
857
- if (shut)
858
- throw new LivingWorldError('command-invalid', `${decision.name} ${shut}`);
859
- if (decision.ballots?.[player.id] !== undefined)
860
- throw new LivingWorldError('command-invalid', `You have already voted on ${decision.name}`);
861
- const summary = `${player.name} votes ${choice} on ${decision.name}`;
862
- session.commit({ kind: 'attempt', actorId: player.id, placeId: player.placeId, summary, narration: `You vote ${choice} on ${decision.name}.`, outcome: 'succeeded',
863
- minutes: 1, effects: [{ kind: 'ballot', entityId: decision.id, personId: player.id, choice }], causeSeq: null, importance: 4, suggestions: [], ...quiet, observed: summary });
1251
+ const entity = session.state.entities[entityId];
1252
+ if (entity === undefined)
1253
+ return refuse('There is nothing to choose on');
1254
+ const kind = session.state.kinds[entity.kindId];
1255
+ const slot = kind?.properties.find(property => property.id === slotId);
1256
+ if (slot === undefined || slot.type !== 'series')
1257
+ return refuse(`${entity.name} has no choices`);
1258
+ if (slot.options !== undefined && !slot.options.includes(option))
1259
+ return refuse(`${option} is not one of the choices`);
1260
+ if (!entity.knownTo.includes(player.id))
1261
+ return refuse(`${entity.name} is not something ${player.name} knows of`);
1262
+ if (player.departed !== undefined || player.offstage !== undefined || (siteOf(session.state, entity.containerId) !== player.placeId && entity.containerId !== player.id)) {
1263
+ return refuse(`${player.name} is not with ${entity.name} to mark it`);
1264
+ }
1265
+ const entries = Array.isArray(entity.properties[slotId]?.value) ? entity.properties[slotId].value : [];
1266
+ if (entries.some(entry => entry.personId === player.id))
1267
+ return refuse(`${player.name} has already chosen on ${entity.name}`);
1268
+ const env = { self: entityId, actor: player.id, target: player.id, value: option, at: session.state.clock };
1269
+ for (const law of kind?.laws ?? []) {
1270
+ if (law.kind !== 'forbid' || !cueMatches(law.on, slotId))
1271
+ continue;
1272
+ if (law.when !== undefined && !evaluateCondition(session.state, env, law.when))
1273
+ continue;
1274
+ refuse(law.then);
1275
+ }
1276
+ const summary = phrase('choose.summary', { name: player.name, option, entity: entity.name });
1277
+ session.commit({ kind: 'attempt', actorId: player.id, placeId: player.placeId, summary, narration: phrase('choose.narration', { option, name: entity.name }), outcome: 'succeeded',
1278
+ minutes: pace(session.state.calendar, 'speech'), effects: [{ kind: 'cell.add', entityId, slotId, option, personId: player.id }], causeSeq: null, importance: 4, suggestions: [], ...quiet, observed: summary });
864
1279
  }
865
1280
  // Those spoken to, the one who spoke least lately first, so the same few do not always answer.
866
1281
  function byTurn(state, placeId, ids) {
@@ -882,14 +1297,18 @@ function playerMessages(session, rawToIds, rawText) {
882
1297
  throw new LivingWorldError('command-invalid', `${id} cannot receive messages`);
883
1298
  // A message to someone who left still goes, as a note to one who quit would; no answer comes.
884
1299
  const readers = toIds.filter(id => session.state.people[id].departed === undefined);
1300
+ const owed = session.state.schedule.filter(owedSchedule).length;
1301
+ const answered = readers.slice(0, Math.max(0, BOUNDS.pinnedSchedule - owed));
1302
+ const overfull = answered.length < readers.length;
885
1303
  const seq = session.state.revision + 1;
886
1304
  const travel = session.state.messageTravel;
887
1305
  session.commit({
888
1306
  kind: 'message', actorId: player.id, placeId: player.placeId,
889
- summary: `${player.name} sends a message to ${toIds.map(id => personLabel(session.state, id)).join(', ')}${travel ? ` ${travel.how}` : ''}`, narration: null, outcome: null, minutes: MESSAGE_MINUTES,
1307
+ summary: phrase('message.sends', { name: player.name, to: toIds.map(id => personLabel(session.state, id)).join(', '), how: travel ? phrase('message.how', { how: travel.how }) : '' })
1308
+ + (overfull ? phrase('owed.noAnswer') : ''), narration: null, outcome: null, minutes: pace(session.state.calendar, 'message'),
890
1309
  effects: travel ? [dispatch(seq, 0, { fromId: player.id, toIds, text, replies: true })] : [
891
1310
  { kind: 'message', fromId: player.id, toIds, text },
892
- ...readers.map((id) => ({ kind: 'schedule', scheduledId: generatedId(session.state.engine, 'reply', [seq, id]), personId: id, inMinutes: MESSAGE_REPLY_DELAY_MINUTES, intent: text, placeId: null, targetId: player.id, scheduleKind: 'reply' })),
1311
+ ...answered.map((id) => ({ kind: 'schedule', scheduledId: generatedId(session.state.engine, 'reply', [seq, id]), personId: id, inMinutes: pace(session.state.calendar, 'messageReplyDelay'), intent: text, placeId: null, targetId: player.id, scheduleKind: 'reply' })),
893
1312
  ],
894
1313
  causeSeq: null, importance: 3, suggestions: [], ...quiet,
895
1314
  });
@@ -900,7 +1319,7 @@ const SPEECH_THINGS = 8;
900
1319
  const KNOWN_ELSEWHERE = 8;
901
1320
  function knownElsewhere(state, personId, placeId) {
902
1321
  const lastChanged = (entity) => Math.max(entity.introducedSeq, ...Object.values(entity.properties).map(slot => slot.changedSeq));
903
- return Object.values(state.entities).filter(entity => entity.placeId !== placeId && entity.knownTo.includes(personId))
1322
+ return Object.values(state.entities).filter(entity => siteOf(state, entity.containerId) !== placeId && entity.knownTo.includes(personId))
904
1323
  .sort((left, right) => lastChanged(right) - lastChanged(left) || left.id.localeCompare(right.id)).slice(0, KNOWN_ELSEWHERE).map(entity => entity.id);
905
1324
  }
906
1325
  // Where the world says messages travel, a message is handed on now and arrives later.
@@ -925,12 +1344,12 @@ function deliverMessage(session, due) {
925
1344
  effects.push({ kind: 'request.open', requestId: request.requestId, senderId: delivery.fromId, receiverId: readers[0], topic: request.topic });
926
1345
  if (delivery.replies) {
927
1346
  effects.push(...readers.filter(id => !state.people[id].isPlayer && id !== delivery.fromId).map((id) => ({ kind: 'schedule', scheduledId: generatedId(session.state.engine, 'reply', [seq, id]), personId: id,
928
- inMinutes: MESSAGE_REPLY_DELAY_MINUTES, intent: session.state.engine >= FULL_SCHEDULE_INTENT_ENGINE ? delivery.text : delivery.text.slice(0, MAX_LINE), placeId: null, targetId: delivery.fromId, scheduleKind: 'reply' })));
1347
+ inMinutes: pace(session.state.calendar, 'messageReplyDelay'), intent: (delivery.text), placeId: null, targetId: delivery.fromId, scheduleKind: 'reply' })));
929
1348
  }
930
1349
  }
931
1350
  session.commit({
932
1351
  kind: 'message', actorId: null, placeId: null,
933
- summary: readers.length > 0 ? `A message from ${from} reaches ${readers.map(id => personLabel(state, id)).join(', ')}` : `A message from ${from} finds no one to read it`,
1352
+ summary: readers.length > 0 ? phrase('message.reaches', { from, to: readers.map(id => personLabel(state, id)).join(', ') }) : phrase('message.noReader', { from }),
934
1353
  narration: null, outcome: null, minutes: 0, effects, causeSeq: due.sourceSeq || null, importance: due.importance, suggestions: [], ...quiet,
935
1354
  });
936
1355
  return Promise.resolve(true);
@@ -944,7 +1363,7 @@ async function playerWaits(session) {
944
1363
  const untilNext = next ? next.at - session.state.clock : null;
945
1364
  session.commit({
946
1365
  kind: 'wait', actorId: player.id, placeId: player.placeId, summary: untilNext !== null && untilNext > 0 ? `${player.name} waits until something happens` : `${player.name} waits a while`,
947
- narration: null, outcome: null, minutes: untilNext === null ? IDLE_WAIT_MINUTES : untilNext > 0 ? Math.min(untilNext, IDLE_WAIT_MINUTES) : OVERDUE_WAIT_MINUTES, effects: [], causeSeq: null, importance: 1, suggestions: [], ...quiet,
1366
+ narration: null, outcome: null, minutes: untilNext === null ? pace(session.state.calendar, 'idleWait') : untilNext > 0 ? Math.min(untilNext, pace(session.state.calendar, 'idleWait')) : pace(session.state.calendar, 'overdueWait'), effects: [], causeSeq: null, importance: 1, suggestions: [], ...quiet,
948
1367
  });
949
1368
  if (!next)
950
1369
  await idleTick(session);
@@ -960,8 +1379,9 @@ function keepPlaying(session) {
960
1379
  }
961
1380
  const recapCardSchema = endingSchema.extend({ title: z.string().trim().min(1).max(200) });
962
1381
  async function finish(session) {
1382
+ const input = epilogueInput(session.state);
963
1383
  const answer = await session.complete({
964
- role: 'narrator', phase: 'epilogue', system: NARRATOR_EPILOGUE_SYSTEM, input: epilogueInput(session.state), responseSchema: epilogueResponseSchema,
1384
+ role: 'narrator', phase: 'epilogue', system: systemFor('narrator', epilogueResponseSchema, input), input, responseSchema: epilogueResponseSchema,
965
1385
  ...LIVING_INFERENCE_LIMITS.epilogue,
966
1386
  }, null);
967
1387
  const card = recapCardSchema.safeParse(answer);
@@ -981,7 +1401,19 @@ function chooseListeners(state, present) {
981
1401
  const warmth = (id) => Math.abs(state.people[id].relationships[state.playerId]?.warmth ?? 0);
982
1402
  return [...present].sort((a, b) => Number(involved.has(b)) - Number(involved.has(a)) || warmth(b) - warmth(a) || a.localeCompare(b)).slice(0, MAX_REACTORS);
983
1403
  }
984
- async function adjudicate(session, actorId, attempt, finishing = null) {
1404
+ async function adjudicate(...args) {
1405
+ const [session, actorId] = args;
1406
+ if (actorId !== session.state.playerId)
1407
+ return adjudicateBody(...args);
1408
+ session.heldForAnswer += MAX_REACTORS;
1409
+ try {
1410
+ return await adjudicateBody(...args);
1411
+ }
1412
+ finally {
1413
+ session.heldForAnswer -= MAX_REACTORS;
1414
+ }
1415
+ }
1416
+ async function adjudicateBody(session, actorId, attempt, finishing = null, speechCause = null) {
985
1417
  const able = () => {
986
1418
  const actor = session.state.people[actorId];
987
1419
  if (actor.incapacitated)
@@ -996,18 +1428,28 @@ async function adjudicate(session, actorId, attempt, finishing = null) {
996
1428
  // A new act sets aside a long act of the actor's still under way, and tells them; ruling one's end clears it.
997
1429
  const clears = (state) => state.schedule.filter(item => item.kind === 'finish' && item.targetId === actorId)
998
1430
  .map(item => item.id === finishing?.item.id ? { kind: 'unschedule', scheduledId: item.id } : leaveOff(item));
999
- const causeSeq = finishing ? finishing.item.sourceSeq || null : null;
1431
+ const causeSeq = finishing ? finishing.item.sourceSeq || null : speechCause;
1000
1432
  const verb = finishing ? 'finishes' : 'tries';
1001
1433
  const gate = gateAgainst(session.state, actorId, 'act');
1002
1434
  if (gate) {
1003
1435
  // A gate on acting settles the attempt itself; there is nothing for the referee to weigh.
1004
- session.commit({
1005
- kind: 'attempt', actorId, placeId: actor.placeId, summary: `${actor.name} ${verb}: "${attempt}" — failed. ${gate.name} stops ${actor.name}.`.slice(0, 2000),
1006
- narration: `${gate.name} stops ${actor.name}.`, outcome: 'failed', minutes: 1, effects: clears(session.state), causeSeq, importance: 1, suggestions: [], reach: 'here', notice: null,
1436
+ const gateEffects = clears(session.state);
1437
+ const witnesses = witnessesFor(session.state, { actorId, placeId: actor.placeId });
1438
+ const reactors = reactorsFor(session.state, actor.placeId, actorId, witnesses, [], gateEffects);
1439
+ const { now: nowReactors, later: laterReactors } = splitReactors(session, actorId, reactors);
1440
+ const perceived = `${actor.name} ${verb}: "${attempt}" — failed. ${gate.name} stops ${actor.name}.`.slice(0, 2000);
1441
+ const event = session.commit({
1442
+ kind: 'attempt', actorId, placeId: actor.placeId, summary: perceived, observed: perceived,
1443
+ narration: `${gate.name} stops ${actor.name}.`, outcome: 'failed', minutes: pace(session.state.calendar, 'speech'),
1444
+ effects: [...gateEffects, ...laterReactionEffects(session.state, session.state.revision + 1, laterReactors, perceived, actorId, 0)],
1445
+ causeSeq, importance: 1, suggestions: [], reach: 'here', notice: null,
1446
+ ...(({ narrationBasis: 'outcome', reasonShown: true })),
1007
1447
  });
1448
+ await react(session, nowReactors, event, { kind: 'attempt', actorId, text: perceived, narration: null }, 'reaction', true);
1449
+ await reactNearby(session, event);
1008
1450
  return;
1009
1451
  }
1010
- const begun = finishing ? { begunAt: clockLabel(finishing.item.held?.at ?? finishing.item.at), changed: finishing.changed } : undefined;
1452
+ const begun = finishing ? { begunAt: clockLabel(session.state.calendar, finishing.item.held?.at ?? finishing.item.at), changed: finishing.changed } : undefined;
1011
1453
  await resolve(session, {
1012
1454
  phase: 'attempt', actorId, placeId: actor.placeId, kind: 'attempt', causeSeq, extraEffects: [], clears, attempt, finishing: finishing !== null,
1013
1455
  ...(finishing ? { finishingId: finishing.item.id } : {}),
@@ -1035,13 +1477,13 @@ async function finishAct(session, due) {
1035
1477
  // Its actor is told it ended unfinished, and anyone there sees them stop.
1036
1478
  const setAside = () => {
1037
1479
  const now = actor === undefined ? undefined : session.state.people[actor.id];
1038
- session.commit({ kind: 'world', actorId: now?.id ?? null, placeId: now && now.departed === undefined && now.away === undefined ? now.placeId : null,
1039
- summary: `${actor?.name ?? 'Someone'} leaves off: ${due.intent}`.slice(0, 2000), narration: now?.isPlayer ? 'You stop before finishing.' : null,
1040
- observed: `${actor?.name ?? 'Someone'} stops before finishing.`, outcome: null, minutes: 0,
1480
+ session.commit({ kind: 'world', actorId: now?.id ?? null, placeId: now && now.departed === undefined && now.offstage === undefined ? now.placeId : null,
1481
+ summary: phrase('act.leavesOff', { name: actor?.name ?? phrase('detail.someone'), intent: due.intent }).slice(0, 2000), narration: now?.isPlayer ? phrase('act.stop') : null,
1482
+ observed: phrase('act.stops', { name: actor?.name ?? phrase('detail.someone') }), outcome: null, minutes: 0,
1041
1483
  effects: [leaveOff(due)], causeSeq: due.sourceSeq || null, importance: 1, suggestions: [], ...quiet });
1042
1484
  return true;
1043
1485
  };
1044
- if (!actor || actor.incapacitated || actor.departed || actor.away || actor.placeId !== due.placeId || !due.held)
1486
+ if (!actor || actor.incapacitated || actor.departed || actor.offstage || actor.placeId !== due.placeId || !due.held)
1045
1487
  return setAside();
1046
1488
  const held = due.held;
1047
1489
  const state = session.state;
@@ -1059,6 +1501,12 @@ async function finishAct(session, due) {
1059
1501
  ending.effects = [...ending.effects, ...seriousConsequences(state, { actorId: actor.id, placeId: due.placeId, seq: draft.seq, minutes: 0, record: held.record ?? due.intent,
1060
1502
  observed: ending.observed ?? null, reactorIds: held.reactorIds, perceivers: ending.perceivedBy ?? [], effects: fields.effects, notice: ending.notice, nearbyIds: draft.nearbyIds })];
1061
1503
  }
1504
+ const reactorIds = reactorsFor(state, due.placeId, actor.id, ending.perceivedBy ?? witnesses, held.reactorIds, ending.effects);
1505
+ const { now: nowReactors, later: laterReactors } = splitReactors(session, actor.id, reactorIds);
1506
+ const perceived = perceivedAct(actor.name, ending.observed ?? null);
1507
+ if (laterReactors.length > 0)
1508
+ ending.effects = [...ending.effects,
1509
+ ...laterReactionEffects(state, session.state.revision + 1, laterReactors, perceived, actor.id, 0)];
1062
1510
  let event = null;
1063
1511
  try {
1064
1512
  event = session.commit(ending);
@@ -1068,8 +1516,7 @@ async function finishAct(session, due) {
1068
1516
  throw error;
1069
1517
  }
1070
1518
  if (event) {
1071
- const reactorIds = held.reactorIds.filter(id => event.perceivedBy?.includes(id) && presentCharacters(session.state, due.placeId, actor.id).includes(id));
1072
- await react(session, reactorIds, event, { kind: 'attempt', actorId: actor.id, text: event.observed ?? `${actor.name} acts nearby.`, narration: null }, 'reaction', true);
1519
+ await react(session, nowReactors, event, { kind: 'attempt', actorId: actor.id, text: perceived, narration: null }, 'reaction', true);
1073
1520
  await reactNearby(session, event);
1074
1521
  return true;
1075
1522
  }
@@ -1092,6 +1539,58 @@ async function finishAct(session, due) {
1092
1539
  // The Game Master rules; the reducer checks; an unacceptable ruling goes back once with
1093
1540
  // its reasons. Then the people there react, someone nearby may notice, and a shock
1094
1541
  // leaves every witness deciding what to do about it.
1542
+ function propertyOf(kind, id) {
1543
+ if (kind === undefined)
1544
+ return undefined;
1545
+ for (const property of kind.properties)
1546
+ if (property.id === id)
1547
+ return property;
1548
+ return undefined;
1549
+ }
1550
+ function rulingProse(state, ruling) {
1551
+ const out = [
1552
+ { field: 'narration', text: ruling.narration },
1553
+ { field: 'record', text: ruling.record },
1554
+ ];
1555
+ if (ruling.observed !== null)
1556
+ out.push({ field: 'observed', text: ruling.observed });
1557
+ if (ruling.settlement !== null)
1558
+ out.push({ field: 'settlement', text: ruling.settlement });
1559
+ if (ruling.newTension !== null)
1560
+ out.push({ field: 'newTension.title', text: ruling.newTension.title }, { field: 'newTension.summary', text: ruling.newTension.summary });
1561
+ if (ruling.newKind !== null)
1562
+ out.push({ field: 'stateNewKind.name', text: ruling.newKind.name }, { field: 'stateNewKind.meaning', text: ruling.newKind.meaning });
1563
+ for (const note of ruling.noted)
1564
+ out.push({ field: 'stateNoted.text', text: note.text });
1565
+ for (const effect of ruling.effects) {
1566
+ if (typeof effect.text === 'string')
1567
+ out.push({ field: 'effect.text', text: effect.text });
1568
+ if (typeof effect.name === 'string')
1569
+ out.push({ field: 'effect.name', text: effect.name });
1570
+ if (typeof effect.condition === 'string')
1571
+ out.push({ field: 'effect.condition', text: effect.condition });
1572
+ if (typeof effect.role === 'string')
1573
+ out.push({ field: 'effect.role', text: effect.role });
1574
+ if (effect.kind === 'property.set' && typeof effect.value === 'string') {
1575
+ const entity = typeof effect.entityId === 'string' ? state.entities[effect.entityId] : undefined;
1576
+ const property = entity === undefined || typeof effect.propertyId !== 'string' ? undefined : propertyOf(state.kinds[entity.kindId], effect.propertyId);
1577
+ if (property === undefined || property.type === 'text')
1578
+ out.push({ field: 'effect.value', text: effect.value });
1579
+ }
1580
+ if (effect.initialProperties !== undefined) {
1581
+ const kind = typeof effect.kindId === 'string' ? state.kinds[effect.kindId] : undefined;
1582
+ for (const [key, value] of Object.entries(effect.initialProperties)) {
1583
+ if (typeof value !== 'string')
1584
+ continue;
1585
+ const property = propertyOf(kind, key);
1586
+ if (property !== undefined && property.type !== 'text')
1587
+ continue;
1588
+ out.push({ field: `effect.initialProperties.${key}`, text: value });
1589
+ }
1590
+ }
1591
+ }
1592
+ return out;
1593
+ }
1095
1594
  async function resolve(session, job) {
1096
1595
  let errors = [];
1097
1596
  let extraRepair = false;
@@ -1105,10 +1604,11 @@ async function resolve(session, job) {
1105
1604
  asked = session.state;
1106
1605
  const input = job.input(errors, true, focusIds);
1107
1606
  // The answer may name only what the model was shown.
1108
- return { input, responseSchema: scopedAttemptResponseSchema(input) };
1607
+ const responseSchema = scopedAttemptResponseSchema(input);
1608
+ return { input, responseSchema, system: systemFor('game-master', responseSchema, input, attemptResponseSchema) };
1109
1609
  };
1110
- const answer = await session.complete({ role: 'game-master', phase: job.phase, system: GAME_MASTER_SYSTEM, ...build(), ...LIVING_INFERENCE_LIMITS[job.phase] }, job.actorId, null, build);
1111
- const ruling = parseRuling(answer);
1610
+ const answer = await session.complete({ role: 'game-master', phase: job.phase, ...build(), ...LIVING_INFERENCE_LIMITS[job.phase] }, job.actorId, null, build);
1611
+ const ruling = parseRuling(answer, session.state);
1112
1612
  // A proposed id already held by a saved thing outside this command's view is taken as well.
1113
1613
  const proposedIds = ruling.effects.flatMap(effect => effect.kind === 'entity.create' && typeof effect.entityId === 'string' ? [effect.entityId] : []);
1114
1614
  const usedCreationIds = new Set(proposedIds.length === 0 ? [] : await session.takenEntityIds(proposedIds));
@@ -1126,13 +1626,35 @@ async function resolve(session, job) {
1126
1626
  if (changed.length > 0 && staleRulings < MAX_STALE_RULINGS && session.canSpend()) {
1127
1627
  staleRulings += 1;
1128
1628
  round -= 1;
1129
- session.rejectLast('ruling-stale');
1130
- errors = [`While this was ruled, the scene changed: ${changed.join('; ')}. Rule on the scene as it is now.`];
1629
+ session.rejectLast('ruling-stale', errors);
1630
+ errors = [phrase('ruling.stale', { changed: changed.join('; ') })];
1131
1631
  continue;
1132
1632
  }
1133
1633
  }
1634
+ const scripts = worldScripts(state);
1635
+ const scriptFailures = [];
1636
+ if (scripts.size > 0) {
1637
+ for (const { field, text } of rulingProse(state, ruling)) {
1638
+ for (const script of foreignScripts(scripts, text))
1639
+ scriptFailures.push(phrase('act.scriptForeign', { script, field }));
1640
+ }
1641
+ }
1642
+ const repeatedRequests = new Set();
1643
+ for (const effect of ruling.effects) {
1644
+ if (effect.kind !== 'request.open' || typeof effect.priorId !== 'string')
1645
+ continue;
1646
+ const prior = state.requests.find(request => request.id === effect.priorId);
1647
+ if (prior !== undefined && prior.status === 'open')
1648
+ repeatedRequests.add(effect);
1649
+ }
1650
+ if (repeatedRequests.size > 0) {
1651
+ ruling.effects = ruling.effects.filter(effect => !repeatedRequests.has(effect));
1652
+ session.noteLast([phrase('act.requestsLeftOut', { count: repeatedRequests.size })]);
1653
+ if (ruling.effects.length === 0 && ruling.newKind === null)
1654
+ ruling.kindFit = 'not-needed';
1655
+ }
1134
1656
  if (job.nothingNew?.(ruling)) {
1135
- session.commit({ kind: 'world', actorId: null, placeId, summary: 'Nothing new came of it', narration: null, outcome: null, minutes: 0,
1657
+ session.commit({ kind: 'world', actorId: null, placeId, summary: phrase('ruling.nothingNew'), narration: null, outcome: null, minutes: 0,
1136
1658
  effects: extra, causeSeq: null, importance: 1, suggestions: [], ...quiet, perceivedBy: [] });
1137
1659
  return;
1138
1660
  }
@@ -1148,7 +1670,7 @@ async function resolve(session, job) {
1148
1670
  // Only the player's own act may take a long stretch of the player's time; a character's act or a world
1149
1671
  // happening resolves in a few minutes so the player's clock does not jump while they stand there.
1150
1672
  if (job.actorId !== state.playerId && !session.live()) {
1151
- ruling.minutes = Math.min(ruling.minutes, OTHERS_MAX_MINUTES, Math.max(0, MAX_NONPLAYER_MINUTES_PER_COMMAND - session.nonPlayerMinutes));
1673
+ ruling.minutes = Math.min(ruling.minutes, pace(state.calendar, 'othersMax'), Math.max(0, pace(state.calendar, 'nonPlayerBudget') - session.nonPlayerMinutes));
1152
1674
  }
1153
1675
  const seq = state.revision + 1;
1154
1676
  const translated = ruling.effects.flatMap((effect, index, all) => {
@@ -1156,25 +1678,33 @@ async function resolve(session, job) {
1156
1678
  if (!anonymousCreation(effect) && all.slice(0, index).some(prior => isDeepStrictEqual(prior, effect)))
1157
1679
  return [];
1158
1680
  const result = translateGmEffect(state, effect, seq, index, placeId, usedCreationIds);
1159
- if ('effect' in result) {
1160
- const id = createdIdentity(result.effect);
1681
+ if ('error' in result)
1682
+ return [result];
1683
+ const produced = [result.effect, ...(result.also ?? [])];
1684
+ for (const single of produced) {
1685
+ const id = createdIdentity(single);
1161
1686
  if (id !== null)
1162
1687
  usedCreationIds.add(id);
1163
1688
  }
1164
- return [result];
1689
+ return produced.map(single => ({ effect: single }));
1165
1690
  });
1166
- const failures = translated.filter((item) => 'error' in item).map(item => item.error);
1691
+ const failures = [...scriptFailures, ...translated.filter((item) => 'error' in item).map(item => item.error)];
1692
+ let contradicted = false;
1167
1693
  if (ruling.kindFit === 'missing' && ruling.newKind === null)
1168
- failures.push('stateKindFit missing needs stateNewKind with a valid id, name, and general meaning');
1694
+ failures.push(phrase('act.kindFitMissing'));
1169
1695
  if (ruling.kindFit !== 'missing' && ruling.newKind !== null)
1170
- failures.push('stateNewKind needs stateKindFit missing');
1696
+ failures.push(phrase('act.kindFitNeeds'));
1697
+ if (ruling.kindFit === 'noted' && ruling.noted.length === 0)
1698
+ failures.push(phrase('act.kindFitNoted'));
1699
+ if (ruling.kindFit !== 'noted' && ruling.noted.length > 0)
1700
+ failures.push(phrase('act.notedNeeds'));
1171
1701
  if (ruling.newKind !== null && state.kinds[ruling.newKind.id]) {
1172
- failures.push(`Kind ${ruling.newKind.id} already exists; use it in entity.create or request a different missing kind`);
1702
+ failures.push(phrase('act.kindExists', { id: ruling.newKind.id }));
1173
1703
  }
1174
1704
  const witnesses = witnessesFor(state, { actorId: job.actorId, placeId: placeId });
1175
1705
  const perceivers = job.seenByAll ? witnesses : ruling.perceivedBy ?? witnesses;
1176
1706
  if (new Set(perceivers).size !== perceivers.length || perceivers.some(id => !witnesses.includes(id)))
1177
- failures.push('perceivedBy must name only distinct people present at the act');
1707
+ failures.push(phrase('act.perceivedBy'));
1178
1708
  // An impossible attempt never happened, so it changes nothing but how people feel about the asking.
1179
1709
  const allowedWhenImpossible = new Set(['mood', 'relationship', 'belief']);
1180
1710
  // New places and people come first, so a ruling's other changes may name them in any order.
@@ -1182,51 +1712,59 @@ async function resolve(session, job) {
1182
1712
  const effects = translated.filter((item) => 'effect' in item).map(item => item.effect)
1183
1713
  .filter(effect => ruling.outcome !== 'impossible' || allowedWhenImpossible.has(effect.kind))
1184
1714
  .sort((left, right) => first(left) - first(right));
1715
+ let chainDropped = 0;
1716
+ if (job.chain) {
1717
+ const continues = ruling.chainContinues && job.chain.link < MAX_CHAIN_LINKS;
1718
+ for (let index = effects.length - 1; index >= 0; index -= 1) {
1719
+ const effect = effects[index];
1720
+ if (effect.kind !== 'schedule' || effect.scheduleKind !== 'world')
1721
+ continue;
1722
+ if (continues)
1723
+ effects[index] = { ...effect, chain: job.chain.id, link: job.chain.link + 1 };
1724
+ else {
1725
+ effects.splice(index, 1);
1726
+ chainDropped += 1;
1727
+ }
1728
+ }
1729
+ }
1185
1730
  const objectChanges = new Map();
1186
1731
  // One act takes each person to at most one neighboring place.
1187
1732
  const moved = new Set();
1188
1733
  // A change refused on its own is left out of a happening's last ruling as well.
1189
1734
  const refused = new Set();
1190
1735
  for (const effect of effects) {
1191
- if (job.movesNoMoney && (effect.kind === 'transfer' || effect.kind === 'money')) {
1192
- failures.push('A problem going on by itself moves no money; money moves by acts and by the world\'s own written happenings');
1736
+ if (job.movesNoNumbers && effect.kind === 'shift') {
1737
+ failures.push(phrase('act.noNumber'));
1193
1738
  refused.add(effect);
1194
1739
  continue;
1195
1740
  }
1196
1741
  // A happening moves, sends away or removes no one who was already here: people go by their own decisions.
1197
- if (job.kind === 'world' && (effect.kind === 'move' || effect.kind === 'person.away' || effect.kind === 'person.leave') && state.people[effect.personId]) {
1198
- failures.push(`A happening moves no one; ${state.people[effect.personId].name} goes where they decide to go`);
1742
+ if (job.kind === 'world' && (effect.kind === 'move' || effect.kind === 'person.offstage' || effect.kind === 'person.leave') && state.people[effect.personId]) {
1743
+ failures.push(phrase('act.happeningMovesNoOne', { name: state.people[effect.personId].name }));
1199
1744
  refused.add(effect);
1200
1745
  continue;
1201
1746
  }
1202
1747
  if (effect.kind === 'move' && state.people[effect.personId]?.placeId === effect.placeId) {
1203
- failures.push(`Person ${effect.personId} is already at ${effect.placeId}`);
1748
+ failures.push(phrase('act.alreadyAt', { person: effect.personId, place: effect.placeId }));
1204
1749
  }
1205
1750
  if (effect.kind === 'move' && state.people[effect.personId]
1206
1751
  && !state.places[state.people[effect.personId].placeId].connections.includes(effect.placeId)) {
1207
- failures.push(`Person ${effect.personId} can only go to a neighboring place in one act`);
1752
+ failures.push(phrase('act.oneNeighbor', { person: effect.personId }));
1208
1753
  }
1209
1754
  if (effect.kind === 'move' && moved.has(effect.personId))
1210
- failures.push(`Person ${effect.personId} moves more than once in one act`);
1755
+ failures.push(phrase('act.movesTwice', { person: effect.personId }));
1211
1756
  if (effect.kind === 'move')
1212
1757
  moved.add(effect.personId);
1213
- if (effect.kind === 'entity.create' && effect.placeId !== null && effect.placeId !== placeId) {
1214
- failures.push(`A new ${effect.kindId} must be created at ${placeId}, where this act happens, or belong to no place`);
1758
+ if (effect.kind === 'entity.create' && effect.containerId !== null && siteOf(state, effect.containerId) !== placeId) {
1759
+ failures.push(phrase('act.newKindPlace', { kind: effect.kindId, place: placeId }));
1215
1760
  }
1216
1761
  if (effect.kind === 'object.update') {
1217
1762
  const previous = objectChanges.get(effect.objectId) ?? state.objects[effect.objectId];
1218
1763
  if (!previous)
1219
1764
  continue;
1220
- const next = { placeId: previous.placeId, holderId: previous.holderId,
1221
- ownerId: previous.ownerId, condition: previous.condition };
1222
- if (effect.placeId !== null) {
1223
- next.placeId = effect.placeId;
1224
- next.holderId = null;
1225
- }
1226
- if (effect.holderId !== null) {
1227
- next.holderId = effect.holderId;
1228
- next.placeId = null;
1229
- }
1765
+ const next = { containerId: previous.containerId, ownerId: previous.ownerId, condition: previous.condition };
1766
+ if (effect.containerId !== undefined)
1767
+ next.containerId = effect.containerId;
1230
1768
  if (effect.ownerId !== null)
1231
1769
  next.ownerId = effect.ownerId;
1232
1770
  if (effect.condition !== null)
@@ -1235,28 +1773,29 @@ async function resolve(session, job) {
1235
1773
  }
1236
1774
  }
1237
1775
  // A ruling changes only what is at hand where it happens, and what a happening concerns.
1238
- const heldHere = (holderId) => holderId !== null && state.people[holderId]?.placeId === placeId;
1239
- const where = (thing) => thing.holderId !== null && state.people[thing.holderId]
1240
- ? `with ${state.people[thing.holderId].name} in ${state.places[state.people[thing.holderId].placeId]?.name ?? 'another place'}` : `in ${state.places[thing.placeId ?? '']?.name ?? 'another place'}`;
1241
- const atHand = () => [...Object.values(state.objects).filter(object => object.placeId === placeId || heldHere(object.holderId)).map(object => object.name),
1242
- ...(state.entityPlaceIds[placeId] ?? []).map(id => state.entities[id].name)];
1243
- const elsewhere = (thing) => `${thing.name} is ${where(thing)}, not in ${state.places[placeId].name}, where this happens; things at hand: ${atHand().join(', ') || 'none'}`;
1776
+ const heldHere = (containerId) => containerId !== null && state.people[containerId]?.placeId === placeId;
1777
+ const where = (thing) => thing.containerId !== null && state.people[thing.containerId]
1778
+ ? phrase('thing.with', { name: state.people[thing.containerId].name, place: state.places[state.people[thing.containerId].placeId]?.name ?? phrase('thing.anotherPlace') }) : phrase('thing.in', { place: state.places[thing.containerId ?? '']?.name ?? phrase('thing.anotherPlace') });
1779
+ const atHand = () => [...Object.values(state.objects).filter(object => object.containerId === placeId || heldHere(object.containerId)).map(object => object.name),
1780
+ ...entitiesHere(state, placeId).map(id => state.entities[id].name)];
1781
+ const elsewhere = (thing) => phrase('thing.elsewhere', { name: thing.name, where: where(thing), place: state.places[placeId].name, things: atHand().join(', ') || phrase('thing.none') });
1244
1782
  for (const effect of effects) {
1245
1783
  if (effect.kind === 'object.update') {
1246
1784
  const object = state.objects[effect.objectId];
1247
- if (object && object.id !== job.concerns && object.placeId !== placeId && !heldHere(object.holderId)) {
1785
+ if (object && object.id !== job.concerns && object.containerId !== placeId && !heldHere(object.containerId)) {
1248
1786
  failures.push(elsewhere(object));
1249
1787
  refused.add(effect);
1250
1788
  }
1251
1789
  // A thing may be put down here, or thrown or pushed next door, but not sent further.
1252
- else if (effect.placeId !== null && effect.placeId !== placeId && !state.places[placeId].connections.includes(effect.placeId)) {
1253
- failures.push(`${object?.name ?? effect.objectId} can only go to ${state.places[placeId].name}, where this happens, or next door`);
1790
+ else if (effect.containerId !== undefined && effect.containerId !== null && state.places[effect.containerId] !== undefined
1791
+ && effect.containerId !== placeId && !state.places[placeId].connections.includes(effect.containerId)) {
1792
+ failures.push(phrase('thing.nextDoor', { name: object?.name ?? effect.objectId, place: state.places[placeId].name }));
1254
1793
  refused.add(effect);
1255
1794
  }
1256
1795
  }
1257
- const entityId = effect.kind === 'entity.condition' || effect.kind === 'property.set' || effect.kind === 'relation.set' || effect.kind === 'entity.move' ? effect.entityId : null;
1796
+ const entityId = effect.kind === 'entity.condition' || effect.kind === 'cell.add' || effect.kind === 'property.set' || effect.kind === 'relation.set' || effect.kind === 'entity.move' ? effect.entityId : null;
1258
1797
  const entity = entityId === null ? undefined : state.entities[entityId];
1259
- if (entity && entity.id !== job.concerns && entity.placeId !== null && entity.placeId !== placeId) {
1798
+ if (entity && entity.id !== job.concerns && entity.containerId !== null && siteOf(state, entity.containerId) !== placeId) {
1260
1799
  failures.push(elsewhere(entity));
1261
1800
  refused.add(effect);
1262
1801
  }
@@ -1265,8 +1804,7 @@ async function resolve(session, job) {
1265
1804
  const restated = new Set();
1266
1805
  for (const [id, changed] of objectChanges) {
1267
1806
  const original = state.objects[id];
1268
- if (changed.placeId === original.placeId && changed.holderId === original.holderId
1269
- && changed.ownerId === original.ownerId && changed.condition === original.condition) {
1807
+ if (changed.containerId === original.containerId && changed.ownerId === original.ownerId && changed.condition === original.condition) {
1270
1808
  for (const effect of effects)
1271
1809
  if (effect.kind === 'object.update' && effect.objectId === id)
1272
1810
  restated.add(effect);
@@ -1277,6 +1815,9 @@ async function resolve(session, job) {
1277
1815
  restated.add(effect);
1278
1816
  if (effect.kind === 'relation.set' && state.entities[effect.entityId]?.relations[effect.relationId]?.targetId === effect.targetId)
1279
1817
  restated.add(effect);
1818
+ if (effect.kind === 'cell.add' && Array.isArray(state.entities[effect.entityId]?.properties[effect.slotId]?.value)
1819
+ && state.entities[effect.entityId].properties[effect.slotId].value.some(entry => entry.option === effect.option && entry.personId === effect.personId))
1820
+ restated.add(effect);
1280
1821
  }
1281
1822
  for (let index = effects.length - 1; index >= 0; index -= 1)
1282
1823
  if (restated.has(effects[index]))
@@ -1284,33 +1825,86 @@ async function resolve(session, job) {
1284
1825
  // Only the player's own act writes or signs a paper in the player's name; restating one as it already is writes nothing.
1285
1826
  if (job.actorId !== state.playerId) {
1286
1827
  const player = state.people[state.playerId].name;
1287
- const writer = job.actorId === null ? 'A happening' : state.people[job.actorId].name;
1828
+ const writer = job.actorId === null ? phrase('happening.name') : state.people[job.actorId].name;
1829
+ const kindOf = (entityId) => state.entities[entityId]?.kindId
1830
+ ?? effects.find((effect) => effect.kind === 'entity.create' && effect.entityId === entityId)?.kindId;
1288
1831
  for (const effect of effects) {
1289
- const inPlayerName = effect.kind === 'entity.create' ? effect.initialProperties?.author === state.playerId
1290
- : effect.kind === 'property.set' && (effect.propertyId === 'author' && effect.value === state.playerId
1291
- || effect.propertyId === 'signed' && effect.value === true && state.entities[effect.entityId]?.properties.author?.value === state.playerId);
1832
+ const inPlayerName = effect.kind === 'entity.create'
1833
+ ? Object.entries(effect.initialProperties ?? {}).some(([slot, value]) => value === state.playerId
1834
+ && state.kinds[effect.kindId]?.properties.find(property => property.id === slot)?.perActor === true)
1835
+ : effect.kind === 'cell.add' && effect.personId === state.playerId ? true
1836
+ : effect.kind === 'property.set' && effect.value === state.playerId
1837
+ && state.kinds[kindOf(effect.entityId) ?? '']?.properties.find(property => property.id === effect.propertyId)?.perActor === true;
1292
1838
  if (!inPlayerName)
1293
1839
  continue;
1294
1840
  failures.push(`${writer} writes or signs nothing in ${player}'s name; only ${player}'s own act does. Hand on a paper that already exists, or name its real writer`);
1295
1841
  refused.add(effect);
1296
1842
  }
1297
1843
  }
1298
- const objectiveEffectKinds = new Set([
1299
- 'entity.create', 'property.set', 'relation.set', 'move', 'take', 'drop', 'object.update', 'entity.move', 'entity.condition',
1300
- 'place.create', 'person.create', 'money', 'transfer', 'hold', 'role', 'incapacitate', 'request.open',
1301
- ]);
1844
+ repairRulingOutcome(ruling, effects);
1845
+ const composed = (job.kind === 'attempt') && job.actorId !== null
1846
+ && job.attempt !== undefined && (ruling.outcome === 'failed' || ruling.outcome === 'impossible');
1847
+ if (composed) {
1848
+ ruling.visibleObjectIds = [];
1849
+ for (const name of unknownNames(state, job.actorId, ruling.reason)) {
1850
+ failures.push(phrase('act.reasonHidden', { name, actor: state.people[job.actorId].name }));
1851
+ }
1852
+ }
1853
+ const unbackedVisible = [];
1854
+ if ((ruling.visibleObjectIds.length > 0)) {
1855
+ const changed = effects.filter(effect => !refused.has(effect));
1856
+ const atHand = (id) => {
1857
+ const object = state.objects[id];
1858
+ if (object)
1859
+ return object.containerId === placeId || object.containerId !== null && state.people[object.containerId]?.placeId === placeId;
1860
+ const entity = state.entities[id];
1861
+ return entity !== undefined && (entity.containerId === placeId || entity.containerId !== null && state.people[entity.containerId]?.placeId === placeId);
1862
+ };
1863
+ for (const id of ruling.visibleObjectIds) {
1864
+ if (!atHand(id))
1865
+ continue;
1866
+ const touched = changed.some(effect => effect.kind === 'object.update' && effect.objectId === id
1867
+ || effect.kind === 'entity.condition' && effect.entityId === id
1868
+ || effect.kind === 'cell.add' && effect.entityId === id
1869
+ || effect.kind === 'entity.move' && effect.entityId === id
1870
+ || effect.kind === 'property.set' && effect.entityId === id);
1871
+ if (!touched)
1872
+ unbackedVisible.push(id);
1873
+ }
1874
+ }
1875
+ if (unbackedVisible.length > 0) {
1876
+ ruling.visibleObjectIds = ruling.visibleObjectIds.filter(id => !unbackedVisible.includes(id));
1877
+ session.noteLast([`${unbackedVisible.length} visible objects had no typed change and were left out`]);
1878
+ }
1879
+ if (job.actorId === state.playerId && job.attempt !== undefined && ruling.observed === job.attempt) {
1880
+ failures.push(phrase('act.playerWords'));
1881
+ }
1302
1882
  for (const effect of effects)
1303
1883
  if (effect.kind === 'request.open' && effect.senderId !== job.actorId) {
1304
- failures.push('request sender must be the actor');
1884
+ failures.push(phrase('act.requestSender'));
1305
1885
  }
1306
1886
  if (ruling.kindFit === 'complete' && (ruling.outcome === 'succeeded' || ruling.outcome === 'partial')
1307
- && !effects.some(effect => objectiveEffectKinds.has(effect.kind)) && restated.size === 0
1887
+ && !effects.some(effect => OBJECTIVE_EFFECT_KINDS.has(effect.kind)) && restated.size === 0
1308
1888
  && ruling.settledTensionId === null && ruling.newTension === null) {
1309
- failures.push('stateKindFit complete needs an objective typed change, such as entity.create or property.set; if nothing lasting changed, answer not-needed');
1889
+ failures.push(phrase('act.kindFitComplete'));
1310
1890
  }
1311
1891
  if (ruling.newKind !== null && !state.kinds[ruling.newKind.id]) {
1312
1892
  effects.push({ kind: 'kind.request', request: ruling.newKind });
1313
1893
  }
1894
+ for (const note of ruling.noted)
1895
+ effects.push({ kind: 'note', facet: note.facet, text: note.text, kindId: note.kindId });
1896
+ if ((job.kind === 'attempt' && job.actorId !== null)) {
1897
+ for (const contactId of ruling.contactIds) {
1898
+ const contact = state.people[contactId];
1899
+ if (!contact || contact.id === job.actorId || contact.isPlayer || contact.departed !== undefined)
1900
+ continue;
1901
+ const requestId = generatedId(state.engine, 'request', [seq, contactId]);
1902
+ const words = (job.attempt ?? ruling.record).slice(0, MAX_TEXT);
1903
+ effects.push({ kind: 'schedule', scheduledId: generatedId(state.engine, 'reply', [seq, contactId]), personId: contactId,
1904
+ inMinutes: pace(state.calendar, 'contactAnswer'), intent: words, placeId: null, targetId: job.actorId, scheduleKind: 'reply', decision: { kind: 'ask', id: requestId } });
1905
+ effects.push({ kind: 'request.open', requestId, senderId: job.actorId, receiverId: contactId, topic: words.slice(0, MAX_LINE) });
1906
+ }
1907
+ }
1314
1908
  const normViolations = job.actorId !== null && ruling.actionKind !== null && ruling.outcome !== 'impossible'
1315
1909
  ? normViolationsFor(state, job.actorId, placeId, ruling.actionKind) : [];
1316
1910
  effects.push(...normViolations);
@@ -1318,7 +1912,7 @@ async function resolve(session, job) {
1318
1912
  if (ruling.settledTensionId !== null) {
1319
1913
  const tension = state.tensions.find(candidate => candidate.id === ruling.settledTensionId && candidate.status === 'open');
1320
1914
  if (!tension)
1321
- failures.push(`settledTensionId ${ruling.settledTensionId} is not an open tension`);
1915
+ failures.push(phrase('act.settledTension', { id: ruling.settledTensionId }));
1322
1916
  else
1323
1917
  effects.push({ kind: 'tension.update', tensionId: tension.id, status: 'settled', note: (ruling.settlement ?? ruling.narration).slice(0, 2000) });
1324
1918
  }
@@ -1338,13 +1932,27 @@ async function resolve(session, job) {
1338
1932
  if (ruling.newTension.visible && !ruling.visibleTensionIds.includes(tensionId))
1339
1933
  ruling.visibleTensionIds.push(tensionId);
1340
1934
  }
1341
- const sensory = signalNotice(state, effects, ruling.observed) ?? (ruling.signalChannel === null ? null
1342
- : `${SIGNAL_NOTICES[ruling.signalChannel]} from ${state.places[placeId].name}.`);
1935
+ const channelNotice = ruling.signalChannel === null ? undefined : state.channels[ruling.signalChannel]?.notice;
1936
+ const sensory = signalNotice(state, effects, ruling.observed) ?? (channelNotice === undefined ? null
1937
+ : `${channelNotice} from ${state.places[placeId].name}.`);
1343
1938
  const affectedPlaces = new Set(effects.flatMap(effect => effect.kind === 'place.condition' ? [effect.placeId] : []));
1344
1939
  const reach = job.reach ? job.reach.reach : ruling.reach === 'here' || sensory === null ? 'here'
1345
1940
  : ruling.reach === 'everywhere' && affectedPlaces.size > 1 ? 'everywhere' : 'nearby';
1346
- const notice = job.reach ? job.reach.notice ?? sensory ?? `Something happens at ${state.places[placeId].name}.` : reach === 'here' ? null : sensory;
1941
+ const notice = job.reach ? job.reach.notice ?? sensory ?? phrase('happening.at', { place: state.places[placeId].name }) : reach === 'here' ? null : sensory;
1347
1942
  const known = (ids) => ids.filter(id => state.entities[id] !== undefined || state.objects[id] !== undefined);
1943
+ const composedOutcome = composed;
1944
+ if (composedOutcome) {
1945
+ const failedActor = state.people[job.actorId];
1946
+ const words = job.attempt ?? '';
1947
+ ruling.observed = ruling.reason.length === 0
1948
+ ? phrase('act.triesOutcome', { name: failedActor.name, words, outcome: String(ruling.outcome) })
1949
+ : phrase('act.triesFailed', { name: failedActor.name, words, why: ruling.reason });
1950
+ ruling.narration = failedActor.isPlayer
1951
+ ? ruling.reason.length === 0
1952
+ ? phrase('act.try', { attempt: words, outcome: String(ruling.outcome) })
1953
+ : phrase('act.tryFailed', { words, why: ruling.reason })
1954
+ : ruling.observed;
1955
+ }
1348
1956
  const draft = session.draft({
1349
1957
  kind: job.kind, actorId: job.actorId, placeId: placeId,
1350
1958
  summary: job.summary(ruling).slice(0, 2000),
@@ -1352,10 +1960,14 @@ async function resolve(session, job) {
1352
1960
  perceivedBy: perceivers,
1353
1961
  visibleObjectIds: ruling.visibleObjectIds,
1354
1962
  visibleTensionIds: ruling.visibleTensionIds,
1355
- ...(state.engine >= THING_MEMORY_ENGINE && known(ruling.thingIds).length > 0 ? { thingIds: known(ruling.thingIds) } : {}),
1963
+ ...((known(ruling.thingIds).length > 0) ? { thingIds: known(ruling.thingIds) } : {}),
1356
1964
  narration: ruling.narration, outcome: ruling.outcome, minutes: ruling.minutes, effects: [...extra, ...effects], causeSeq: job.causeSeq, importance, suggestions: [],
1357
- reach, notice,
1965
+ ...((job.kind === 'attempt') ? { narrationBasis: composedOutcome ? 'outcome' : 'model' } : {}),
1966
+ ...(composedOutcome ? { reasonShown: ruling.reason.length > 0, ...(ruling.reason.length === 0 ? {} : { reason: ruling.reason }) } : {}),
1967
+ reach, notice, channel: job.reach ? null : ruling.signalChannel,
1358
1968
  });
1969
+ if (chainDropped > 0)
1970
+ draft.droppedEffects = (draft.droppedEffects ?? 0) + chainDropped;
1359
1971
  if (job.kind === 'attempt' && importance >= SHOCK_IMPORTANCE && ruling.outcome !== 'impossible') {
1360
1972
  draft.effects = [...draft.effects, ...seriousConsequences(state, { actorId: job.actorId, placeId, seq, minutes: ruling.minutes, record: ruling.record,
1361
1973
  observed: ruling.observed, reactorIds: ruling.reactorIds, perceivers, effects, notice, nearbyIds: draft.nearbyIds })];
@@ -1374,29 +1986,41 @@ async function resolve(session, job) {
1374
1986
  .filter(property => property.requiredOnCreate && !entity.properties[property.id])
1375
1987
  .map(property => property.id);
1376
1988
  if (missing.length > 0)
1377
- failures.push(`New ${entity.kindId} needs ${missing.join(', ')} before this act ends`);
1989
+ failures.push(phrase('act.newKindNeeds', { kind: entity.kindId, missing: missing.join(', ') }));
1378
1990
  }
1379
1991
  for (const effect of draft.effects) {
1380
1992
  if (effect.kind !== 'incapacitate')
1381
1993
  continue;
1382
1994
  if (!blockedByGate(proposed, effect.personId, 'incapacitate')
1383
1995
  || blockedByGate(state, effect.personId, 'incapacitate')) {
1384
- failures.push('incapacitate needs a newly active typed gate on that person');
1996
+ failures.push(phrase('act.incapacitateGate'));
1385
1997
  }
1386
1998
  }
1999
+ const said = [draft.narration, draft.summary, draft.observed, ruling.settlement,
2000
+ ...(ruling.newTension === null ? [] : [ruling.newTension.title, ruling.newTension.summary]),
2001
+ ...ruling.noted.map(note => note.text)];
2002
+ for (const contradiction of proseContradictions(proposed, said)) {
2003
+ contradicted = true;
2004
+ failures.push(phrase('act.contradictsCell', {
2005
+ name: contradiction.entityName,
2006
+ said: contradiction.saysTrue ? contradiction.label : phrase('detail.not', { label: contradiction.label }),
2007
+ actual: contradiction.actual ? contradiction.label : phrase('detail.not', { label: contradiction.label }),
2008
+ }));
2009
+ }
1387
2010
  }
1388
2011
  catch (error) {
1389
2012
  failures.push(error instanceof Error ? error.message : String(error));
1390
2013
  }
1391
2014
  }
2015
+ const nextExtraRepair = job.kind === 'attempt' && errors.length > 0 && !isDeepStrictEqual(errors, failures);
2016
+ const retrying = round === 0 || (round === 1 && nextExtraRepair && session.canSpend());
1392
2017
  let dropped = 0;
1393
2018
  if (failures.length > 0) {
1394
- session.rejectLast('effects-invalid');
1395
- extraRepair = job.kind === 'attempt' && errors.length > 0 && !isDeepStrictEqual(errors, failures);
1396
- const retrying = round === 0 || (round === 1 && extraRepair && session.canSpend());
2019
+ session.rejectLast('effects-invalid', failures);
2020
+ extraRepair = nextExtraRepair;
1397
2021
  // A happening the world wrote happens even when some of its changes cannot be made: its last
1398
2022
  // ruling keeps what the world accepts, and counts what it leaves out.
1399
- const kept = job.kind === 'world' && !retrying ? acceptedPart(state, draft, extra, effects.filter(effect => effect.kind !== 'kind.request' && !refused.has(effect))) : null;
2023
+ const kept = job.kind === 'world' && !retrying && !contradicted ? acceptedPart(state, draft, extra, effects.filter(effect => effect.kind !== 'kind.request' && !refused.has(effect))) : null;
1400
2024
  if (kept === null) {
1401
2025
  // Each repair hears every mistake so far, so fixing one does not bring back another.
1402
2026
  errors = [...new Set([...errors, ...failures])];
@@ -1409,8 +2033,9 @@ async function resolve(session, job) {
1409
2033
  draft.droppedEffects = dropped;
1410
2034
  }
1411
2035
  // In a live world a long act only begins now. Its ruling is held, and what it tells and changes
1412
- // applies when its time has passed; those present see it begin.
1413
- if (job.attempt !== undefined && !job.finishing && job.actorId !== null && session.live() && ruling.minutes > LONG_ACT_MINUTES
2036
+ // applies when its time has passed; those present see it begin. When the world has no room left
2037
+ // to owe its end, it is ruled at once, as in a turn-mode world.
2038
+ if (job.attempt !== undefined && !job.finishing && job.actorId !== null && session.live() && ruling.minutes > pace(state.calendar, 'longAct')
1414
2039
  && (ruling.outcome === 'succeeded' || ruling.outcome === 'partial')) {
1415
2040
  const actor = state.people[job.actorId];
1416
2041
  const { seq: _seq, at: _at, witnessIds: _witnesses, nearbyIds: _nearby, ...fields } = draft;
@@ -1418,24 +2043,76 @@ async function resolve(session, job) {
1418
2043
  const held = { fields: { ...fields, effects }, record: ruling.record,
1419
2044
  standing: Object.fromEntries(referencedIds(job.actorId, ruling).filter(id => state.people[id] || state.objects[id] || state.entities[id])
1420
2045
  .map(id => [id, standing(state, id)])), reactorIds: ruling.reactorIds.filter(id => state.people[id]) };
1421
- session.commit({
1422
- kind: 'attempt', actorId: job.actorId, placeId, summary: `${actor.name} begins: "${job.attempt}"`.slice(0, 2000),
1423
- narration: actor.isPlayer ? `You begin: ${job.attempt}`.slice(0, 2000) : null, observed: draft.observed, perceivedBy: perceivers, visibleObjectIds: [], visibleTensionIds: [],
2046
+ const finishId = `finish-${seq}`;
2047
+ const begin = {
2048
+ kind: 'attempt', actorId: job.actorId, placeId, summary: phrase('act.begins', { name: actor.name, attempt: job.attempt }).slice(0, 2000),
2049
+ narration: actor.isPlayer ? phrase('act.begin', { attempt: job.attempt }).slice(0, 2000) : null, observed: draft.observed, perceivedBy: perceivers, visibleObjectIds: [], visibleTensionIds: [],
1424
2050
  outcome: null, minutes: ruling.minutes, causeSeq: job.causeSeq, importance: 2, suggestions: [], reach: 'here', notice: null,
1425
- effects: [...extra, { kind: 'schedule', scheduledId: `finish-${seq}`, personId: null, inMinutes: ruling.minutes, intent: state.engine >= FULL_SCHEDULE_INTENT_ENGINE ? job.attempt : job.attempt.slice(0, MAX_LINE),
2051
+ effects: [...extra, { kind: 'schedule', scheduledId: finishId, personId: null, inMinutes: Math.max(pace(state.calendar, 'speech'), ruling.minutes), intent: (job.attempt),
1426
2052
  placeId, targetId: job.actorId, scheduleKind: 'finish', held }],
1427
- });
1428
- return;
2053
+ };
2054
+ if (applyLivingEvent(state, session.draft(begin)).schedule.some(item => item.id === finishId)) {
2055
+ session.commit(begin);
2056
+ return;
2057
+ }
1429
2058
  }
2059
+ const reactorIds = job.kind === 'attempt'
2060
+ ? reactorsFor(session.state, placeId, job.actorId, perceivers, ruling.reactorIds, effects)
2061
+ : ruling.reactorIds.filter(id => perceivers.includes(id) && presentCharacters(session.state, placeId, job.actorId).includes(id)).slice(0, MAX_REACTORS);
2062
+ const split = job.kind === 'attempt' ? splitReactors(session, job.actorId, reactorIds) : { now: reactorIds, later: [] };
2063
+ const nowReactors = split.now;
2064
+ const laterReactors = split.later;
2065
+ const perceived = job.kind === 'attempt' ? perceivedAct(session.state.people[job.actorId].name, draft.observed ?? null) : draft.observed ?? draft.summary;
2066
+ if (laterReactors.length > 0)
2067
+ draft.effects = [...draft.effects,
2068
+ ...laterReactionEffects(session.state, draft.seq, laterReactors, perceived, job.actorId, session.live() ? 0 : ruling.minutes)];
1430
2069
  const event = session.commit(draft);
1431
- const trigger = job.trigger(ruling);
1432
- const reactorIds = ruling.reactorIds.filter(id => perceivers.includes(id) && presentCharacters(session.state, placeId, job.actorId).includes(id)).slice(0, MAX_REACTORS);
1433
- await react(session, reactorIds, event, trigger, 'reaction', true);
2070
+ const trigger = job.kind === 'attempt' ? { ...job.trigger(ruling), text: perceived } : job.trigger(ruling);
2071
+ await react(session, nowReactors, event, trigger, 'reaction', true);
1434
2072
  await reactNearby(session, event);
1435
2073
  return;
1436
2074
  }
2075
+ if (job.kind === 'attempt' && job.actorId !== null && job.finishingId === undefined) {
2076
+ const actor = session.state.people[job.actorId];
2077
+ if (actor && !actor.incapacitated) {
2078
+ const words = job.attempt ?? '';
2079
+ const failedEffects = job.clears ? job.clears(session.state) : [];
2080
+ const witnesses = witnessesFor(session.state, { actorId: actor.id, placeId: actor.placeId });
2081
+ const reactors = reactorsFor(session.state, actor.placeId, actor.id, witnesses, [], failedEffects);
2082
+ const { now: nowReactors, later: laterReactors } = splitReactors(session, actor.id, reactors);
2083
+ const perceived = phrase('act.triesOutcome', { name: actor.name, words, outcome: 'failed' }).slice(0, 2000);
2084
+ const event = session.commit({
2085
+ kind: 'attempt', actorId: job.actorId, placeId: actor.placeId,
2086
+ summary: perceived,
2087
+ narration: actor.isPlayer ? phrase('act.try', { attempt: words, outcome: 'failed' }).slice(0, 2000) : null,
2088
+ observed: perceived,
2089
+ outcome: 'failed', minutes: pace(session.state.calendar, 'speech'),
2090
+ effects: [...failedEffects, ...laterReactionEffects(session.state, session.state.revision + 1, laterReactors, perceived, actor.id, 0)],
2091
+ causeSeq: job.causeSeq,
2092
+ importance: 1, suggestions: [], reach: 'here', notice: null,
2093
+ ...(({ narrationBasis: 'outcome', reasonShown: false })),
2094
+ });
2095
+ await react(session, nowReactors, event, { kind: 'attempt', actorId: actor.id, text: perceived, narration: null }, 'reaction', true);
2096
+ await reactNearby(session, event);
2097
+ return;
2098
+ }
2099
+ }
1437
2100
  throw new LivingWorldError('inference-invalid', `The Game Master proposed changes the world cannot accept: ${errors.join('; ')}`);
1438
2101
  }
2102
+ function repairRulingOutcome(ruling, effects) {
2103
+ if (ruling.outcome !== 'failed' && ruling.outcome !== 'impossible')
2104
+ return;
2105
+ if (!effects.some(effect => OBJECTIVE_EFFECT_KINDS.has(effect.kind)))
2106
+ return;
2107
+ if (ruling.outcome === 'failed') {
2108
+ ruling.outcome = 'partial';
2109
+ return;
2110
+ }
2111
+ for (let index = effects.length - 1; index >= 0; index -= 1) {
2112
+ if (OBJECTIVE_EFFECT_KINDS.has(effects[index].kind))
2113
+ effects.splice(index, 1);
2114
+ }
2115
+ }
1439
2116
  // The changes of a ruling the world accepts, one at a time in order: each must apply after those kept
1440
2117
  // before it and change something. Null when even the ruling's own bookkeeping does not apply.
1441
2118
  function acceptedPart(state, draft, extra, effects) {
@@ -1474,10 +2151,10 @@ function standing(state, id) {
1474
2151
  return `person ${person.placeId} ${person.incapacitated} ${person.held?.byId ?? ''} ${person.held ? 'held' : ''}`;
1475
2152
  const object = state.objects[id];
1476
2153
  if (object)
1477
- return `object ${object.placeId} ${object.holderId} ${object.condition}`;
2154
+ return `object ${siteOf(state, object.containerId)} ${object.containerId ?? ''} ${object.condition}`;
1478
2155
  const entity = state.entities[id];
1479
2156
  if (entity)
1480
- return `entity ${entity.placeId} ${entity.holderId ?? ''} ${entity.condition ?? ''} ${Math.max(entity.introducedSeq, ...Object.values(entity.properties).map(slot => slot.changedSeq), ...Object.values(entity.relations).map(slot => slot.changedSeq))}`;
2157
+ return `entity ${siteOf(state, entity.containerId)} ${entity.containerId ?? ''} ${entity.condition ?? ''} ${Math.max(entity.introducedSeq, ...Object.values(entity.properties).map(slot => slot.changedSeq), ...Object.values(entity.relations).map(slot => slot.changedSeq))}`;
1481
2158
  return 'absent';
1482
2159
  }
1483
2160
  // What a serious act leaves behind: a later look at its consequences unless the ruling already set
@@ -1485,20 +2162,20 @@ function standing(state, id) {
1485
2162
  function seriousConsequences(state, act) {
1486
2163
  const out = [];
1487
2164
  const worldFollowups = act.effects.filter((effect) => effect.kind === 'schedule' && effect.personId === null);
1488
- if (!worldFollowups.some(effect => effect.inMinutes >= act.minutes + 30)) {
2165
+ if (!worldFollowups.some(effect => effect.inMinutes >= act.minutes + pace(state.calendar, 'aftermathGap'))) {
1489
2166
  const later = worldFollowups.length > 0;
1490
- out.push({ kind: 'schedule', scheduledId: `aftermath-${act.seq}`, personId: null, inMinutes: act.minutes + (later ? 45 : 15),
1491
- intent: `${later ? 'Check lasting consequences' : 'Check what has changed'} after this serious event: ${act.record}`.slice(0, 600),
2167
+ out.push({ kind: 'schedule', scheduledId: `aftermath-${act.seq}`, personId: null, inMinutes: act.minutes + pace(state.calendar, later ? 'aftermathLater' : 'aftermathSoon'),
2168
+ intent: (later ? phrase('aftermath.later', { record: act.record }) : phrase('aftermath.soon', { record: act.record })).slice(0, 600),
1492
2169
  placeId: act.placeId, targetId: null, scheduleKind: 'world' });
1493
2170
  }
1494
- const present = presentCharacters(state, act.placeId, act.actorId).filter(id => act.perceivers.includes(id));
2171
+ const present = inStoryOrder(state, presentCharacters(state, act.placeId, act.actorId)).filter(id => act.perceivers.includes(id) && !state.people[id].incidental);
1495
2172
  const witnesses = [...new Set([...act.reactorIds, ...present])].filter(id => present.includes(id)).slice(0, MAX_REACTORS);
1496
2173
  witnesses.forEach((id, index) => {
1497
- out.push(...shockPlanEffects(state, id, generatedId(state.engine, 'shock', [act.seq, id]), `Decide what to do about what you observed: ${act.observed}`.slice(0, 600), act.minutes + SHOCK_PLAN_DELAY_MINUTES + 5 * index, act.actorId));
2174
+ out.push(...shockPlanEffects(state, id, generatedId(state.engine, 'shock', [act.seq, id]), phrase('decision.observed', { observed: String(act.observed) }).slice(0, 600), act.minutes + pace(state.calendar, 'shockPlanDelay') + pace(state.calendar, 'shockSpacing') * index, act.actorId));
1498
2175
  });
1499
2176
  if (act.notice !== null) {
1500
- out.push(...act.nearbyIds.filter(id => state.people[id] && !state.people[id].isPlayer && !state.people[id].incapacitated && !state.people[id].away && !state.people[id].departed).slice(0, MAX_REACTORS)
1501
- .flatMap((id, index) => shockPlanEffects(state, id, generatedId(state.engine, 'nearby-shock', [act.seq, id]), `Decide what to do about what you noticed: ${act.notice}`.slice(0, 600), act.minutes + SHOCK_PLAN_DELAY_MINUTES + 5 * index, null)));
2177
+ out.push(...inStoryOrder(state, act.nearbyIds).filter(id => !state.people[id].isPlayer && !state.people[id].incapacitated && !state.people[id].offstage && !state.people[id].departed).slice(0, MAX_REACTORS)
2178
+ .flatMap((id, index) => shockPlanEffects(state, id, generatedId(state.engine, 'nearby-shock', [act.seq, id]), phrase('decision.noticed', { notice: String(act.notice) }).slice(0, 600), act.minutes + pace(state.calendar, 'shockPlanDelay') + pace(state.calendar, 'shockSpacing') * index, null)));
1502
2179
  }
1503
2180
  return out;
1504
2181
  }
@@ -1517,10 +2194,10 @@ function nowStanding(state, id) {
1517
2194
  const person = state.people[id];
1518
2195
  const object = state.objects[id];
1519
2196
  if (person)
1520
- return person.incapacitated ? `${person.name} can no longer act` : `${person.name} is now at ${state.places[person.placeId]?.name ?? person.placeId}`;
2197
+ return person.incapacitated ? phrase('standing.cannotAct', { name: person.name }) : phrase('standing.at', { name: person.name, place: state.places[person.placeId]?.name ?? person.placeId });
1521
2198
  if (object)
1522
- return `${object.name} is now ${object.holderId ? `held by ${personLabel(state, object.holderId)}` : `at ${state.places[object.placeId ?? '']?.name ?? 'an unknown place'}`}, ${object.condition}`;
1523
- return `${state.entities[id]?.name ?? id} has changed`;
2199
+ return object.containerId !== null && state.people[object.containerId] ? phrase('standing.held', { name: object.name, holder: personLabel(state, object.containerId), condition: object.condition }) : phrase('standing.atPlace', { name: object.name, place: state.places[object.containerId ?? '']?.name ?? phrase('standing.unknownPlace'), condition: object.condition });
2200
+ return phrase('standing.changed', { name: state.entities[id]?.name ?? id });
1524
2201
  }
1525
2202
  // The people and things a ruling names whose place or state changed between two states, described for the Game Master.
1526
2203
  function changedReferences(before, after, actorId, ruling) {
@@ -1531,12 +2208,12 @@ function changedReferences(before, after, actorId, ruling) {
1531
2208
  const person = after.people[id];
1532
2209
  const object = after.objects[id];
1533
2210
  if (person)
1534
- changed.push(person.incapacitated && !before.people[id]?.incapacitated ? `${person.name} can no longer act`
1535
- : `${person.name} is now at ${after.places[person.placeId]?.name ?? person.placeId}`);
2211
+ changed.push(person.incapacitated && !before.people[id]?.incapacitated ? phrase('standing.cannotAct', { name: person.name })
2212
+ : phrase('standing.at', { name: person.name, place: after.places[person.placeId]?.name ?? person.placeId }));
1536
2213
  else if (object)
1537
- changed.push(`${object.name} is now ${object.holderId ? `held by ${personLabel(after, object.holderId)}` : `at ${after.places[object.placeId ?? '']?.name ?? 'an unknown place'}`}, ${object.condition}`);
2214
+ changed.push(object.containerId !== null && after.people[object.containerId] ? phrase('standing.held', { name: object.name, holder: personLabel(after, object.containerId), condition: object.condition }) : phrase('standing.atPlace', { name: object.name, place: after.places[object.containerId ?? '']?.name ?? phrase('standing.unknownPlace'), condition: object.condition }));
1538
2215
  else
1539
- changed.push(`${after.entities[id]?.name ?? id} has changed`);
2216
+ changed.push(phrase('standing.changed', { name: after.entities[id]?.name ?? id }));
1540
2217
  }
1541
2218
  return changed;
1542
2219
  }
@@ -1574,7 +2251,8 @@ async function reactNearby(session, event) {
1574
2251
  };
1575
2252
  // Someone the event brings into a person's room is seen arriving; that person does not hear a commotion.
1576
2253
  const arriving = candidates.filter(id => arrivalFor(state, event, id) !== null);
1577
- const [chosen] = [...(arriving.length > 0 ? arriving : candidates)].sort((a, b) => closeness(b) - closeness(a) || a.localeCompare(b));
2254
+ const story = new Map(Object.keys(state.people).map((id, index) => [id, index]));
2255
+ const [chosen] = [...(arriving.length > 0 ? arriving : candidates)].sort((a, b) => closeness(b) - closeness(a) || (story.get(a) ?? 0) - (story.get(b) ?? 0));
1578
2256
  const arrival = arrivalFor(state, event, chosen);
1579
2257
  const mover = event.effects.find(effect => effect.kind === 'move' && effect.placeId === state.people[chosen].placeId && effect.personId !== chosen);
1580
2258
  if (arrival !== null && mover?.kind === 'move') {
@@ -1582,12 +2260,12 @@ async function reactNearby(session, event) {
1582
2260
  return;
1583
2261
  }
1584
2262
  const from = event.placeId ? state.places[event.placeId]?.name ?? null : null;
1585
- await react(session, [chosen], event, { kind: 'nearby', actorId: null, text: event.notice ?? 'a commotion', narration: null, noticedFrom: from }, 'reaction', true);
2263
+ await react(session, [chosen], event, { kind: 'nearby', actorId: null, text: event.notice ?? phrase('notice.commotion'), narration: null, noticedFrom: from }, 'reaction', true);
1586
2264
  }
1587
2265
  function uniqueIds(values) {
1588
2266
  return [...new Set(values.filter((id) => typeof id === 'string'))];
1589
2267
  }
1590
- function parseRuling(answer) {
2268
+ function parseRuling(answer, state) {
1591
2269
  const value = answer;
1592
2270
  const outcomes = ['succeeded', 'partial', 'failed', 'impossible'];
1593
2271
  if (!value || typeof value !== 'object' || typeof value.narration !== 'string' || value.narration.trim() === '' || typeof value.outcome !== 'string' || !outcomes.includes(value.outcome) || !Array.isArray(value.stateUpdates ?? value.effects)) {
@@ -1602,6 +2280,7 @@ function parseRuling(answer) {
1602
2280
  return {
1603
2281
  narration,
1604
2282
  record: (typeof value.record === 'string' && value.record.trim() !== '' ? value.record.trim() : narration).slice(0, 600),
2283
+ reason: typeof value.reason === 'string' ? value.reason.trim().slice(0, 300) : '',
1605
2284
  observed: typeof value.observed === 'string' && value.observed.trim() !== '' ? value.observed.trim().slice(0, 600) : null,
1606
2285
  // Naming the same person or thing twice in these lists says nothing more, so each is kept once.
1607
2286
  perceivedBy: Array.isArray(value.perceivedBy) ? uniqueIds(value.perceivedBy) : null,
@@ -1610,10 +2289,10 @@ function parseRuling(answer) {
1610
2289
  thingIds: Array.isArray(value.thingIds) ? uniqueIds(value.thingIds).slice(0, 8) : [],
1611
2290
  visibleTensionIds: Array.isArray(value.visibleTensionIds) ? uniqueIds(value.visibleTensionIds) : [],
1612
2291
  outcome: value.outcome,
1613
- minutes: clampInt(value.minutes, 0, 240, 5),
2292
+ minutes: clampInt(value.minutes, 0, 1_000_000_000, pace(state.calendar, 'actDefault')),
1614
2293
  importance: clampInt(value.importance, 1, 10, 4),
1615
2294
  reach: value.reach === 'nearby' || value.reach === 'everywhere' ? value.reach : 'here',
1616
- signalChannel: typeof value.signalChannel === 'string' && SIGNAL_SENSES.includes(value.signalChannel) ? value.signalChannel : null,
2295
+ signalChannel: typeof value.signalChannel === 'string' && state.channels[value.signalChannel] !== undefined ? value.signalChannel : null,
1617
2296
  effects: updates.map(flattenShape).filter((effect) => effect !== null && typeof effect === 'object' && typeof effect.kind === 'string').slice(0, 8)
1618
2297
  .map(normalizeGmEffect),
1619
2298
  reactorIds: Array.isArray(value.reactorIds) ? value.reactorIds.filter((id) => typeof id === 'string') : [],
@@ -1623,8 +2302,21 @@ function parseRuling(answer) {
1623
2302
  ? { title: newTension.title, summary: newTension.summary, participantIds: Array.isArray(newTension.participantIds) ? newTension.participantIds.filter((id) => typeof id === 'string') : [], visible: newTension.visible === true }
1624
2303
  : null,
1625
2304
  newKind: kindRequestSchema.safeParse(newKind).success ? kindRequestSchema.parse(newKind) : null,
1626
- kindFit: kindFit === 'complete' || kindFit === 'missing' ? kindFit : 'not-needed',
2305
+ noted: Array.isArray(value.stateNoted) ? value.stateNoted.flatMap((item) => {
2306
+ if (item === null || typeof item !== 'object')
2307
+ return [];
2308
+ const note = item;
2309
+ if (typeof note.facet !== 'string' || !/^[a-z0-9][a-z0-9-]{0,63}$/u.test(note.facet))
2310
+ return [];
2311
+ if (typeof note.text !== 'string' || note.text.trim().length === 0)
2312
+ return [];
2313
+ const kindId = typeof note.kindId === 'string' && state.kinds[note.kindId] !== undefined ? note.kindId : null;
2314
+ return [{ facet: note.facet, text: note.text.trim().slice(0, MAX_LINE), kindId }];
2315
+ }).slice(0, 3) : [],
2316
+ kindFit: kindFit === 'complete' || kindFit === 'missing' || kindFit === 'noted' ? kindFit : 'not-needed',
1627
2317
  actionKind: typeof value.actionKind === 'string' && /^[a-z0-9][a-z0-9-]{0,63}$/u.test(value.actionKind) ? value.actionKind : null,
2318
+ contactIds: Array.isArray(value.contactIds) ? uniqueIds(value.contactIds).slice(0, 4) : [],
2319
+ chainContinues: value.chainContinues === true,
1628
2320
  };
1629
2321
  }
1630
2322
  // A change arrives as { kind, values }; answers recorded before engine 26 are already flat.
@@ -1644,7 +2336,8 @@ function normalizeGmEffect(effect) {
1644
2336
  connections: effect.connections ?? null, participantIds: effect.participantIds ?? null,
1645
2337
  status: effect.status ?? null, entityId: effect.entityId ?? null, kindId: effect.kindId ?? null,
1646
2338
  propertyId: effect.propertyId ?? null, relationId: effect.relationId ?? null, roleId: effect.roleId ?? null,
1647
- priorId: effect.priorId ?? null, value: effect.value ?? null, choice: effect.choice ?? null,
2339
+ priorId: effect.priorId ?? null, value: effect.value ?? null, choice: effect.choice ?? null, slot: effect.slot ?? null,
2340
+ slotId: effect.slotId ?? null, option: effect.option ?? null,
1648
2341
  ...(effect.initialProperties ? { initialProperties: effect.initialProperties } : {}),
1649
2342
  };
1650
2343
  }
@@ -1685,24 +2378,23 @@ export function translateGmEffect(state, record, seq, index, placeId = null, use
1685
2378
  const id = need(record.objectId, 'objectId', 'object.update');
1686
2379
  // A written thing or token: a holder or a place moves it; otherwise its visible condition changes.
1687
2380
  if (state.entities[id]) {
1688
- if (record.targetId !== null)
1689
- effect = { kind: 'entity.move', entityId: id, holderId: record.targetId, placeId: null };
1690
- else if (record.placeId !== null)
1691
- effect = { kind: 'entity.move', entityId: id, holderId: null, placeId: record.placeId };
1692
- else if (record.condition !== null)
1693
- effect = { kind: 'entity.condition', entityId: id, condition: record.condition.slice(0, 200), ...side(record.name) };
1694
- else
2381
+ const moved = record.targetId !== null || record.placeId !== null
2382
+ ? { kind: 'entity.move', entityId: id, containerId: record.targetId ?? record.placeId } : null;
2383
+ const changed = record.condition !== null ? { kind: 'entity.condition', entityId: id, condition: record.condition.slice(0, 200), ...side(record.name) } : null;
2384
+ if (moved === null && changed === null)
1695
2385
  throw new Error(`${state.entities[id].name} needs a condition, a holder or a place`);
2386
+ return moved === null ? { effect: changed } : changed === null ? { effect: moved } : { effect: moved, also: [changed] };
1696
2387
  }
1697
2388
  else
1698
- effect = { kind: 'object.update', objectId: id, condition: record.condition, ...(record.condition === null ? {} : side(record.name)), placeId: record.targetId === null ? record.placeId : null, holderId: record.targetId, ownerId: record.personId };
2389
+ effect = { kind: 'object.update', objectId: id, condition: record.condition, ...(record.condition === null ? {} : side(record.name)),
2390
+ ...(record.targetId === null && record.placeId === null ? {} : { containerId: record.targetId ?? record.placeId }), ownerId: record.personId };
1699
2391
  break;
1700
2392
  }
1701
2393
  // A written thing or token that is somewhere changes hands the same way an object does.
1702
2394
  case 'take': {
1703
2395
  const id = need(record.objectId, 'objectId', 'take');
1704
- effect = state.entities[id] ? { kind: 'entity.move', entityId: id, holderId: need(record.personId, 'personId', 'take'), placeId: null }
1705
- : { kind: 'object.update', objectId: id, condition: null, placeId: null, holderId: need(record.personId, 'personId', 'take'), ownerId: null };
2396
+ effect = state.entities[id] ? { kind: 'entity.move', entityId: id, containerId: need(record.personId, 'personId', 'take') }
2397
+ : { kind: 'object.update', objectId: id, condition: null, containerId: need(record.personId, 'personId', 'take'), ownerId: null };
1706
2398
  break;
1707
2399
  }
1708
2400
  case 'drop': {
@@ -1710,12 +2402,12 @@ export function translateGmEffect(state, record, seq, index, placeId = null, use
1710
2402
  const to = record.placeId ?? placeId;
1711
2403
  if (to === null)
1712
2404
  throw new Error('drop needs a placeId');
1713
- effect = state.entities[id] ? { kind: 'entity.move', entityId: id, holderId: null, placeId: to }
1714
- : { kind: 'object.update', objectId: id, condition: null, placeId: to, holderId: null, ownerId: null };
2405
+ effect = state.entities[id] ? { kind: 'entity.move', entityId: id, containerId: to }
2406
+ : { kind: 'object.update', objectId: id, condition: null, containerId: to, ownerId: null };
1715
2407
  break;
1716
2408
  }
1717
2409
  case 'object.create':
1718
- effect = { kind: 'object.create', objectId: newId('object', record.objectId), name: need(record.name, 'name', 'object.create'), summary: need(record.text, 'text', 'object.create'), placeId: record.targetId === null ? record.placeId : null, holderId: record.targetId, ownerId: record.personId, condition: record.condition ?? 'intact' };
2410
+ effect = { kind: 'object.create', objectId: newId('object', record.objectId), name: need(record.name, 'name', 'object.create'), summary: need(record.text, 'text', 'object.create'), containerId: record.targetId ?? record.placeId, ownerId: record.personId, condition: record.condition ?? 'intact' };
1719
2411
  break;
1720
2412
  case 'place.condition': {
1721
2413
  const placeId = need(record.placeId, 'placeId', 'place.condition');
@@ -1734,7 +2426,7 @@ export function translateGmEffect(state, record, seq, index, placeId = null, use
1734
2426
  const same = (record.personId ? state.people[record.personId] : undefined)
1735
2427
  ?? Object.values(state.people).find(person => person.departed === undefined && person.name === name);
1736
2428
  if (same)
1737
- throw new Error(`${same.name} (${same.id}) is already in the story${same.isPlayer ? ' as the player' : same.away ? ', away for now' : `, in ${state.places[same.placeId]?.name ?? same.placeId}`}; bring in someone new or no one`);
2429
+ throw new Error(`${same.name} (${same.id}) is already in the story${same.isPlayer ? ' as the player' : same.offstage ? ', offstage for now' : `, in ${state.places[same.placeId]?.name ?? same.placeId}`}; bring in someone new or no one`);
1738
2430
  // A newcomer knows only what they see and are told here, never what the referee knows about them.
1739
2431
  // Their role is said once, beside their name; when they came is kept as a time, not as words that age.
1740
2432
  const role = record.role ?? 'Newcomer';
@@ -1747,26 +2439,21 @@ export function translateGmEffect(state, record, seq, index, placeId = null, use
1747
2439
  if (wants === null)
1748
2440
  throw new Error('person.create needs text: what brought them here and what they want now');
1749
2441
  effect = { kind: 'person.create', personId: newId('person', record.personId), name: need(record.name, 'name', 'person.create'), role,
1750
- summary: `First seen at ${state.places[at]?.name ?? at}.`, persona: 'Decide from what you see and are told, and from what brought you here.', placeId: at, pronouns: null, wants };
2442
+ summary: phrase('person.firstSeen', { place: state.places[at]?.name ?? at }), persona: phrase('person.persona'), placeId: at, pronouns: null, wants };
1751
2443
  break;
1752
2444
  }
1753
2445
  case 'person.leave':
1754
2446
  effect = { kind: 'person.leave', personId: need(record.personId, 'personId', 'person.leave'), reason: need(record.text, 'text', 'person.leave').slice(0, 600) };
1755
2447
  break;
1756
- case 'person.away':
1757
- effect = { kind: 'person.away', personId: need(record.personId, 'personId', 'person.away'),
1758
- minutes: Math.max(AWAY_MINUTES.min, Math.min(AWAY_MINUTES.max, record.minutes ?? AWAY_MINUTES.min)), reason: need(record.text, 'text', 'person.away').slice(0, 600) };
1759
- break;
1760
- case 'money':
1761
- effect = { kind: 'money', personId: need(record.personId, 'personId', 'money'), delta: record.amount ?? 0 };
1762
- if (effect.delta === 0)
1763
- throw new Error('money needs a non-zero amount');
2448
+ case 'person.offstage':
2449
+ effect = { kind: 'person.offstage', personId: need(record.personId, 'personId', 'person.offstage'),
2450
+ minutes: Math.max(pace(state.calendar, 'offstageMin'), Math.min(state.calendar.day, record.minutes ?? pace(state.calendar, 'offstageMin'))), why: need(record.text, 'text', 'person.offstage').slice(0, 600) };
1764
2451
  break;
1765
- case 'transfer': {
2452
+ case 'shift': {
1766
2453
  const amount = record.amount ?? 0;
1767
2454
  if (!(amount > 0))
1768
- throw new Error('transfer needs a positive amount');
1769
- effect = { kind: 'transfer', fromId: record.personId?.trim() || null, toId: record.targetId?.trim() || null, amount: Math.round(amount * 100) / 100 };
2455
+ throw new Error('shift needs a positive amount');
2456
+ effect = { kind: 'shift', slotId: need(record.slot, 'slot', 'shift'), fromId: record.personId?.trim() || null, toId: record.targetId?.trim() || null, amount: Math.round(amount * 100) / 100 };
1770
2457
  break;
1771
2458
  }
1772
2459
  case 'relationship':
@@ -1807,7 +2494,7 @@ export function translateGmEffect(state, record, seq, index, placeId = null, use
1807
2494
  case 'schedule': {
1808
2495
  if (record.personId !== null && record.personId.trim() !== '')
1809
2496
  throw new Error('A character must choose their own plan; schedule only a world happening');
1810
- effect = { kind: 'schedule', scheduledId: fresh('world'), personId: null, inMinutes: Math.max(1, record.minutes ?? 30), intent: need(record.text, 'text', 'schedule'), placeId: record.placeId ?? placeId, targetId: record.targetId, scheduleKind: 'world' };
2497
+ effect = { kind: 'schedule', scheduledId: fresh('world'), personId: null, inMinutes: Math.max(pace(state.calendar, 'speech'), record.minutes ?? pace(state.calendar, 'defaultActivity')), intent: need(record.text, 'text', 'schedule'), placeId: record.placeId ?? placeId, targetId: record.targetId, scheduleKind: 'world' };
1811
2498
  if (effect.placeId === null)
1812
2499
  throw new Error('a world happening needs a placeId');
1813
2500
  break;
@@ -1841,31 +2528,73 @@ export function translateGmEffect(state, record, seq, index, placeId = null, use
1841
2528
  // Making again a thing that is right here would make a second copy of it; an id taken by a
1842
2529
  // thing elsewhere is only a clash of names, and the new thing gets its own id.
1843
2530
  const existing = state.entities[proposedId] ?? state.objects[proposedId];
1844
- const atHand = existing !== undefined && placeId !== null && (existing.placeId === placeId
1845
- || existing.holderId !== null && state.people[existing.holderId]?.placeId === placeId);
2531
+ const containerId = existing === undefined ? null : siteOf(state, existing.containerId);
2532
+ const atHand = existing !== undefined && placeId !== null && containerId === placeId;
1846
2533
  if (existing && atHand)
1847
2534
  throw new Error(`${proposedId} already exists as ${existing.name}: change it, or leave it`);
2535
+ const kind = state.kinds[need(record.kindId, 'kindId', 'entity.create')];
2536
+ const decision = isDecisionKind(kind);
2537
+ if (decision) {
2538
+ const { initialProperties } = record;
2539
+ const { settles } = (initialProperties ?? {});
2540
+ const twin = Object.values(state.entities).find(candidate => {
2541
+ const { settles: candidateSettles } = candidate.properties;
2542
+ return candidate.kindId === record.kindId
2543
+ && (candidate.containerId === (record.personId ?? record.placeId ?? null) || (typeof settles === 'string' && candidateSettles?.value === settles));
2544
+ });
2545
+ if (twin)
2546
+ throw new Error(`${twin.name} is already open: use it`);
2547
+ }
2548
+ const twin = Object.values(state.entities).find(candidate => candidate.kindId === record.kindId && candidate.name === record.name
2549
+ && candidate.containerId === (record.personId ?? record.placeId ?? null));
2550
+ if (twin)
2551
+ throw new Error(`${record.name} already exists as ${twin.name}: change it, or leave it`);
2552
+ const initial = record.initialProperties === undefined ? undefined : { ...record.initialProperties };
2553
+ if (initial !== undefined && kind !== undefined) {
2554
+ for (const property of kind.properties) {
2555
+ if (property.type === 'series' && initial[property.id] !== undefined)
2556
+ throw new Error(`${property.id} is a series; add to it after the thing exists`);
2557
+ if (property.perActor !== true)
2558
+ continue;
2559
+ if (initial[property.id] === undefined && record.personId !== null)
2560
+ initial[property.id] = record.personId;
2561
+ }
2562
+ }
1848
2563
  effect = { kind: 'entity.create', entityId: newId('entity', proposedId),
1849
2564
  // A thing made into someone's hand is where they stand, whatever place the ruling named.
1850
2565
  kindId: need(record.kindId, 'kindId', 'entity.create'), name: need(record.name, 'name', 'entity.create'),
1851
- placeId: record.placeId ?? (record.personId && state.people[record.personId] ? state.people[record.personId].placeId : null),
1852
- ...(record.initialProperties ? { initialProperties: record.initialProperties } : {}),
1853
- ...(record.condition?.trim() ? { condition: record.condition.trim().slice(0, 200) } : {}), ...(record.personId ? { holderId: record.personId } : {}),
1854
- ...(record.kindId === 'decision' && record.participantIds?.length ? { memberIds: record.participantIds } : {}) };
2566
+ containerId: record.personId ?? record.placeId ?? null,
2567
+ ...(initial ? { initialProperties: initial } : {}),
2568
+ ...(record.condition?.trim() ? { condition: record.condition.trim().slice(0, 200) } : {}) };
1855
2569
  break;
1856
2570
  }
1857
- case 'ballot': {
1858
- if (record.choice !== 'yes' && record.choice !== 'no' && record.choice !== 'abstain')
1859
- throw new Error('ballot needs choice');
1860
- effect = { kind: 'ballot', entityId: need(record.entityId, 'entityId', 'ballot'), personId: need(record.personId, 'personId', 'ballot'), choice: record.choice };
2571
+ case 'property.set': {
2572
+ const entityId = need(record.entityId, 'entityId', 'property.set');
2573
+ const propertyId = need(record.propertyId, 'propertyId', 'property.set');
2574
+ const slot = state.entities[entityId] === undefined ? undefined : state.kinds[state.entities[entityId].kindId]?.properties.find(property => property.id === propertyId);
2575
+ if (slot?.type === 'series')
2576
+ throw new Error(`${propertyId} is a series; add to it instead`);
2577
+ effect = { kind: 'property.set', entityId, propertyId, value: slot?.perActor === true ? record.value ?? record.personId ?? null : record.value ?? null };
1861
2578
  break;
1862
2579
  }
1863
- case 'property.set':
1864
- effect = { kind: 'property.set', entityId: need(record.entityId, 'entityId', 'property.set'), propertyId: need(record.propertyId, 'propertyId', 'property.set'), value: record.value ?? null };
1865
- break;
1866
2580
  case 'relation.set':
1867
2581
  effect = { kind: 'relation.set', entityId: need(record.entityId, 'entityId', 'relation.set'), relationId: need(record.relationId, 'relationId', 'relation.set'), targetId: record.targetId };
1868
2582
  break;
2583
+ case 'cell.add': {
2584
+ const entityId = need(record.entityId, 'entityId', 'cell.add');
2585
+ const entity = state.entities[entityId];
2586
+ if (!entity)
2587
+ throw new Error('cell.add needs a thing at hand');
2588
+ const slotId = need(record.slotId, 'slotId', 'cell.add');
2589
+ const slot = state.kinds[entity.kindId]?.properties.find(property => property.id === slotId);
2590
+ if (!slot || slot.type !== 'series')
2591
+ throw new Error(`${entity.name} has no series ${slotId}`);
2592
+ const option = need(record.option, 'option', 'cell.add');
2593
+ if (slot.options !== undefined && !slot.options.includes(option))
2594
+ throw new Error(`${option} is not one of ${slot.options.join(', ')} for ${entity.name}`);
2595
+ effect = { kind: 'cell.add', entityId, slotId, option, personId: need(record.personId, 'personId', 'cell.add') };
2596
+ break;
2597
+ }
1869
2598
  case 'request.open': {
1870
2599
  const senderId = need(record.personId, 'personId', 'request.open');
1871
2600
  const receiverId = need(record.targetId, 'targetId', 'request.open');
@@ -1882,22 +2611,22 @@ export function translateGmEffect(state, record, seq, index, placeId = null, use
1882
2611
  }
1883
2612
  default: throw new Error(`Unknown effect kind ${String(record.kind)}`);
1884
2613
  }
1885
- if (effect.kind === 'object.update' && effect.holderId !== null
1886
- && effect.holderId !== state.objects[effect.objectId]?.holderId
2614
+ if (effect.kind === 'object.update' && effect.containerId !== undefined && effect.containerId !== null && state.people[effect.containerId] !== undefined
2615
+ && effect.containerId !== state.objects[effect.objectId]?.containerId
1887
2616
  && state.objects[effect.objectId]?.singlePersonMovable === false) {
1888
2617
  throw new Error(`${state.objects[effect.objectId].name} cannot be carried by one person; make the part that moves a new thing, or leave it where it is`);
1889
2618
  }
1890
- const moving = effect.kind === 'object.update' && effect.holderId !== null ? { thing: state.objects[effect.objectId], holderId: effect.holderId }
1891
- : effect.kind === 'entity.move' && effect.holderId !== null ? { thing: state.entities[effect.entityId], holderId: effect.holderId } : null;
2619
+ const moving = effect.kind === 'object.update' && effect.containerId !== undefined && effect.containerId !== null && state.people[effect.containerId] !== undefined
2620
+ ? { thing: state.objects[effect.objectId], holderId: effect.containerId }
2621
+ : effect.kind === 'entity.move' && effect.containerId !== null && state.people[effect.containerId] !== undefined ? { thing: state.entities[effect.entityId], holderId: effect.containerId } : null;
1892
2622
  if (moving?.thing) {
1893
2623
  const holder = state.people[moving.holderId];
1894
- // A held object has no place of its own; a held typed thing is where its holder is.
1895
- const fromPlace = moving.thing.placeId ?? (moving.thing.holderId ? state.people[moving.thing.holderId]?.placeId : null);
2624
+ const fromPlace = siteOf(state, moving.thing.containerId);
1896
2625
  if (holder && fromPlace && fromPlace !== holder.placeId) {
1897
2626
  // The repair hears where the thing is and what is within reach, so it can choose again.
1898
- const atHand = [...Object.values(state.objects).filter(candidate => candidate.placeId === holder.placeId
1899
- || (candidate.holderId !== null && state.people[candidate.holderId]?.placeId === holder.placeId)).map(candidate => candidate.name),
1900
- ...(state.entityPlaceIds[holder.placeId] ?? []).map(id => state.entities[id].name)];
2627
+ const atHand = [...Object.values(state.objects).filter(candidate => candidate.containerId === holder.placeId
2628
+ || (candidate.containerId !== null && state.people[candidate.containerId]?.placeId === holder.placeId)).map(candidate => candidate.name),
2629
+ ...entitiesHere(state, holder.placeId).map(id => state.entities[id].name)];
1901
2630
  throw new Error(`${moving.thing.name} is in ${state.places[fromPlace]?.name ?? fromPlace}, not with ${holder.name} in ${state.places[holder.placeId]?.name ?? holder.placeId}; `
1902
2631
  + (atHand.length > 0 ? `things at hand there: ${atHand.join(', ')}` : 'there is nothing here to hand over'));
1903
2632
  }
@@ -1911,44 +2640,41 @@ export function translateGmEffect(state, record, seq, index, placeId = null, use
1911
2640
  return { error: error instanceof Error ? error.message : String(error) };
1912
2641
  }
1913
2642
  }
1914
- // A vote a character casts in their own answer, on a decision open to them.
1915
- function parseBallot(value) {
1916
- const ballot = value && typeof value === 'object' ? value : null;
1917
- return ballot && typeof ballot.decisionId === 'string' && (ballot.choice === 'yes' || ballot.choice === 'no' || ballot.choice === 'abstain')
1918
- ? { decisionId: ballot.decisionId, choice: ballot.choice } : null;
1919
- }
1920
2643
  // Whether this person already said these very words in a talk still under way; no one says a line twice.
1921
2644
  // An ask still open may be recalled to the one asked once two game hours have passed since it was made
1922
2645
  // or last recalled; a sooner repeat, or one after a refusal, is held back.
1923
2646
  function reminderDue(state, request, personId, targetId) {
1924
- if (!request || state.engine < REMINDER_ENGINE || request.status !== 'open' || request.senderId !== personId || request.receiverId !== targetId)
2647
+ if ((!request) || request.status !== 'open' || request.senderId !== personId || request.receiverId !== targetId)
1925
2648
  return false;
1926
2649
  const last = request.remindedAt ?? request.openedAt;
1927
- return last !== undefined && state.clock - last >= REMINDER_MINUTES;
2650
+ return last !== undefined && state.clock - last >= pace(state.calendar, 'reminder');
2651
+ }
2652
+ export function changesSomething(reaction) {
2653
+ return reaction.request !== null || reaction.requestDecision !== null || reaction.commitmentDecision !== null
2654
+ || reaction.stance !== null || reaction.trust !== 0 || reaction.warmth !== 0 || reaction.belief !== null
2655
+ || reaction.commitment !== null || reaction.newGoal !== null || reaction.goalDone !== null || reaction.plan !== null
2656
+ || reaction.leaveToPlaceId !== null || reaction.endConversation || reaction.tell !== null || reaction.act !== null;
1928
2657
  }
1929
2658
  function saidAlready(state, personId, text) {
1930
2659
  return state.conversations.some(conversation => conversation.endedAt === null && conversation.lines.some(line => line.speakerId === personId && line.text === text));
1931
2660
  }
1932
- // The ballot effect for a vote this person may cast now, among the votes the moment concerns, or none.
1933
- function ballotEffects(state, personId, ballot, concerned) {
1934
- const decision = ballot && (concerned === 'any' || concerned.has(ballot.decisionId)) ? state.entities[ballot.decisionId] : undefined;
1935
- return ballot && decision?.members?.includes(personId) && decision.ballots?.[personId] === undefined && votingShut(state, decision, state.clock) === null
1936
- ? [{ kind: 'ballot', entityId: decision.id, personId, choice: ballot.choice }] : [];
1937
- }
1938
2661
  // Each reactor answers once; an answer that repeats itself or leaves English goes back
1939
2662
  // once with the reason. When the reaction is optional, a silent model means a silent
1940
2663
  // witness; the event it answers is already saved.
1941
2664
  async function react(session, reactorIds, cause, trigger, phase, optional) {
1942
2665
  // People answer one after another, so each hears what those before them said.
1943
2666
  let acted = false;
1944
- for (const id of reactorIds) {
2667
+ for (const [index, id] of reactorIds.entries()) {
1945
2668
  const decidedIn = session.state.people[id]?.placeId;
1946
- const release = await session.takeTurn(id);
2669
+ const answeringPlayer = phase === 'reply' && cause.actorId === session.state.playerId;
2670
+ if (answeringPlayer && answeredLine(session.state, id, cause.seq))
2671
+ continue;
2672
+ const release = await session.takeTurn(id, answeringPlayer);
1947
2673
  let reaction = null;
1948
2674
  try {
1949
2675
  // Someone who walked off, went home or left while an earlier decision of theirs was out answers this moment no more.
1950
- if (decidedIn !== undefined && isHere(session.state, id, decidedIn))
1951
- reaction = await reactAndRecord(session, id, cause, trigger, phase, optional);
2676
+ if (!answeredLine(session.state, id, cause.seq) && decidedIn !== undefined && isHere(session.state, id, decidedIn))
2677
+ reaction = await reactAndRecord(session, id, cause, trigger, phase, optional, (reactorIds.length - index - 1) * 2);
1952
2678
  }
1953
2679
  finally {
1954
2680
  release();
@@ -1964,7 +2690,7 @@ async function react(session, reactorIds, cause, trigger, phase, optional) {
1964
2690
  acted = true;
1965
2691
  session.answeringActs += 1;
1966
2692
  try {
1967
- await adjudicate(session, id, reaction.act);
2693
+ await adjudicate(session, id, reaction.act, null, cause.seq);
1968
2694
  }
1969
2695
  catch (error) {
1970
2696
  if (!(error instanceof LivingWorldError) || (error.code !== 'inference-invalid' && error.code !== 'inference-unavailable'))
@@ -1977,44 +2703,76 @@ async function react(session, reactorIds, cause, trigger, phase, optional) {
1977
2703
  }
1978
2704
  }
1979
2705
  // One person's reaction, decided and recorded; null when they decide nothing.
1980
- async function reactAndRecord(session, id, cause, trigger, phase, optional) {
1981
- const { reaction: decided, dropped, asked } = await decideReaction(session, id, cause, trigger, phase, optional);
1982
- if (!decided)
1983
- return null;
1984
- // Words decided while this person said something else meanwhile, or before someone came into or
1985
- // left their room, answer a moment that has passed.
1986
- const place = session.state.people[id]?.placeId;
1987
- const later = session.state.events.filter(event => event.seq > asked);
1988
- const roomChanged = later.some(event => event.effects.some(effect => effect.kind === 'move' && effect.personId !== id
1989
- && (effect.placeId === place || event.placeId === place)));
1990
- const movedOn = decided.say !== null && (roomChanged || later.some(event => event.actorId === id
1991
- && event.effects.some(effect => effect.kind === 'say' || effect.kind === 'message' || effect.kind === 'dispatch')));
1992
- const reaction = movedOn ? { ...decided, say: null, request: null } : decided;
1993
- const fields = reactionFields(session.state, id, reaction, cause, trigger, dropped + (movedOn ? 1 : 0));
1994
- if (fields)
1995
- session.commit(fields);
1996
- return reaction;
1997
- }
1998
- async function decideReaction(session, id, cause, trigger, phase, optional) {
1999
- if (optional && !session.canSpendOptional())
2706
+ async function reactAndRecord(session, id, cause, trigger, phase, optional, reserve = 0) {
2707
+ const speaking = phase === 'reply' && cause.actorId === session.state.playerId;
2708
+ if (speaking)
2709
+ session.answering(id, true);
2710
+ try {
2711
+ const { reaction: decided, dropped, asked } = await decideReaction(session, id, cause, trigger, phase, optional, reserve);
2712
+ if (!decided)
2713
+ return null;
2714
+ // Words decided while this person said something else meanwhile, or before someone came into or
2715
+ // left their room, answer a moment that has passed.
2716
+ const place = session.state.people[id]?.placeId;
2717
+ const later = session.state.events.filter(event => event.seq > asked);
2718
+ const roomChanged = later.some(event => event.effects.some(effect => effect.kind === 'move' && effect.personId !== id
2719
+ && (effect.placeId === place || event.placeId === place)));
2720
+ const movedOn = decided.say !== null && (roomChanged || later.some(event => event.actorId === id
2721
+ && event.effects.some(effect => effect.kind === 'say' || effect.kind === 'message' || effect.kind === 'dispatch')));
2722
+ const reaction = movedOn ? { ...decided, say: phase === 'reply' ? decided.say : null, request: null } : decided;
2723
+ const fields = reactionFields(session.state, id, reaction, cause, trigger, dropped + (movedOn && !(phase === 'reply' && decided.say !== null) ? 1 : 0));
2724
+ if (fields)
2725
+ session.commit(fields);
2726
+ return reaction;
2727
+ }
2728
+ finally {
2729
+ if (speaking)
2730
+ session.answering(id, false);
2731
+ }
2732
+ }
2733
+ export function reactionAnswerProblems(reaction, state, personId, facts) {
2734
+ const problems = reactionProblems(reaction, state, personId);
2735
+ problems.push(...presenceProblems(reaction, state, personId));
2736
+ if (state.clockRate !== null && reaction.say !== null && saidAgain(state, personId, facts.causeSeq) !== null && !changesSomething(reaction)) {
2737
+ problems.push(phrase('reply.saidAlready'));
2738
+ }
2739
+ const leaving = reaction.leaveToPlaceId !== null && state.places[reaction.leaveToPlaceId] !== undefined;
2740
+ if (facts.phase === 'reply' && reaction.say === null && !leaving && !reaction.endConversation
2741
+ && blockedByGate(state, personId, 'speak') === null && facts.budgetAllows) {
2742
+ problems.push(phrase('reply.answerDirectly'));
2743
+ }
2744
+ const repeat = facts.phase === 'reply' && facts.trigger.kind === 'speech' && facts.trigger.actorId === state.playerId
2745
+ ? answeredAgain(state, personId) : null;
2746
+ if (repeat !== null && repeat.sameAskRepeats > 0 && !changesSomething(reaction)) {
2747
+ problems.push(repeat.sameAskRepeats === 1 ? phrase('reply.repeatedOnce') : phrase('reply.repeatedTimes', { count: repeat.sameAskRepeats }));
2748
+ }
2749
+ return problems;
2750
+ }
2751
+ async function decideReaction(session, id, cause, trigger, phase, optional, reserve = 0) {
2752
+ const answering = cause.actorId === session.state.playerId;
2753
+ if (!session.canSpend())
2754
+ return { reaction: null, dropped: 0, asked: session.state.revision };
2755
+ if (optional && !session.canSpendOptional(answering))
2000
2756
  return { reaction: null, dropped: 0, asked: session.state.revision };
2001
2757
  let errors = [];
2002
2758
  let last = null;
2003
2759
  let asked = session.state.revision;
2004
2760
  for (let round = 0; round < 2; round += 1) {
2005
- if (round > 0 && !(optional ? session.canSpendOptional() : session.canSpend()))
2761
+ if (round > 0 && !(optional ? session.canSpendOptional(answering) : session.canSpend()))
2006
2762
  break;
2007
2763
  try {
2008
2764
  // Each try reads the world as it is when it goes; another event may have landed while the last one was out.
2009
2765
  const build = (focusIds = []) => {
2010
2766
  const state = session.state;
2011
2767
  asked = state.revision;
2012
- const input = characterReactionInput(state, state.people[id], { ...trigger, thingIds: cause.thingIds ?? [] }, true, errors, focusIds);
2013
- return { input, responseSchema: scopedReactionResponseSchema(input) };
2768
+ const input = characterReactionInput(state, state.people[id], { ...trigger, thingIds: trigger.thingIds ?? cause.thingIds ?? [] }, true, errors, focusIds);
2769
+ const responseSchema = scopedReactionResponseSchema(input, session.state.engine);
2770
+ return { input, responseSchema, system: systemFor('character-reaction', responseSchema, input, reactionResponseSchema) };
2014
2771
  };
2015
- const answer = await session.complete({ role: 'character', phase, system: CHARACTER_REACTION_SYSTEM, ...build(), ...LIVING_INFERENCE_LIMITS[phase] }, id, cause.seq, build);
2016
- const reaction = parseReaction(answer);
2017
- const problems = reactionProblems(reaction, session.state, id);
2772
+ const answer = await session.complete({ role: 'character', phase, ...build(), ...LIVING_INFERENCE_LIMITS[phase] }, id, cause.seq, build);
2773
+ const reaction = parseReaction(answer, session.state);
2774
+ const problems = reactionAnswerProblems(reaction, session.state, id, { phase, causeSeq: cause.seq, trigger,
2775
+ budgetAllows: session.calls + 2 + reserve <= MAX_MODEL_CALLS_PER_COMMAND });
2018
2776
  if (problems.length === 0)
2019
2777
  return { reaction, dropped: 0, asked };
2020
2778
  last = reaction;
@@ -2022,7 +2780,7 @@ async function decideReaction(session, id, cause, trigger, phase, optional) {
2022
2780
  // so they still answer; a reaction nobody asked for is not worth a second call.
2023
2781
  if (phase === 'reaction' && problems.every(problem => typeof problem !== 'string' && problem.kind === 'request-already-made'))
2024
2782
  break;
2025
- session.rejectLast('reaction-rejected');
2783
+ session.rejectLast('reaction-rejected', problems.map(problem => typeof problem === 'string' ? problem : problem.kind));
2026
2784
  errors = problems;
2027
2785
  }
2028
2786
  catch (error) {
@@ -2042,24 +2800,44 @@ async function decideReaction(session, id, cause, trigger, phase, optional) {
2042
2800
  const reasking = last.request?.priorId !== undefined && last.request.priorId !== null
2043
2801
  && reactionProblems({ ...last, requestDecision: null }, session.state, id).length > 0;
2044
2802
  const undecidable = last.requestDecision !== null && reactionProblems({ ...last, request: null }, session.state, id).length > 0;
2045
- const kept = { ...last, ...(reasking ? { say: null, request: null } : {}), ...(undecidable ? { requestDecision: null } : {}) };
2046
- return { reaction: kept, dropped: (reasking && last.say !== null ? 1 : 0) + (undecidable ? 1 : 0), asked };
2803
+ const repeated = phase === 'reply' && trigger.kind === 'speech' && trigger.actorId === session.state.playerId
2804
+ ? answeredAgain(session.state, id) : null;
2805
+ const unchanged = repeated !== null && last.say !== null && !changesSomething(last);
2806
+ const absent = presenceProblems(last, session.state, id);
2807
+ const kept = { ...last, ...(reasking ? { say: phase === 'reply' ? last.say : null, request: null } : {}), ...(undecidable ? { requestDecision: null } : {}),
2808
+ ...(absent.length > 0 ? { say: null, waitingOnIds: [] } : {}),
2809
+ ...(unchanged ? { warmth: -1 } : {}) };
2810
+ return { reaction: kept, dropped: (reasking && last.say !== null && phase !== 'reply' ? 1 : 0) + (undecidable ? 1 : 0), asked };
2811
+ }
2812
+ export function presenceProblems(reaction, state, personId) {
2813
+ const person = state.people[personId];
2814
+ if (!person)
2815
+ return [];
2816
+ const present = new Set(peopleAt(state, person.placeId));
2817
+ return [...new Set(reaction.waitingOnIds)].filter(id => id !== personId && !present.has(id))
2818
+ .map(id => ({ kind: 'person-absent', requestId: null, status: null, personId: id }));
2047
2819
  }
2048
- function reactionProblems(reaction, state, personId) {
2820
+ export function reactionProblems(reaction, state, personId) {
2049
2821
  const problems = [];
2822
+ const mine = (request) => request.senderId === personId || request.receiverId === personId;
2050
2823
  if (reaction.request?.priorId) {
2051
2824
  const prior = state.requests.find(request => request.id === reaction.request.priorId);
2052
2825
  if (!prior)
2053
2826
  problems.push({ kind: 'unknown-request', requestId: reaction.request.priorId, status: null });
2827
+ else if (!mine(prior))
2828
+ problems.push({ kind: 'request-not-yours', requestId: null, status: null });
2054
2829
  else if (prior.receiverId === reaction.request.receiverId && !reminderDue(state, prior, personId, reaction.request.receiverId)) {
2055
2830
  problems.push({ kind: 'request-already-made', requestId: prior.id, status: prior.status });
2056
2831
  }
2057
2832
  }
2058
2833
  if (reaction.requestDecision) {
2059
2834
  const request = state.requests.find(item => item.id === reaction.requestDecision.id);
2060
- if (!request || request.receiverId !== personId || request.status !== 'open') {
2061
- problems.push({ kind: 'request-not-open', requestId: reaction.requestDecision.id, status: request?.status ?? null });
2062
- }
2835
+ if (!request)
2836
+ problems.push({ kind: 'request-not-open', requestId: reaction.requestDecision.id, status: null });
2837
+ else if (!mine(request))
2838
+ problems.push({ kind: 'request-not-yours', requestId: null, status: null });
2839
+ else if (request.receiverId !== personId || request.status !== 'open')
2840
+ problems.push({ kind: 'request-not-open', requestId: request.id, status: request.status });
2063
2841
  }
2064
2842
  return problems;
2065
2843
  }
@@ -2074,7 +2852,7 @@ function parsePlanValue(value, fallbackMinutes) {
2074
2852
  return { intent: plan.intent.trim().slice(0, 300), ...(seen === null ? {} : { seen }), placeId: typeof plan.placeId === 'string' ? plan.placeId : null,
2075
2853
  targetId: typeof plan.targetId === 'string' ? plan.targetId : null, inMinutes: clampInt(plan.inMinutes, 1, 100_000, fallbackMinutes) };
2076
2854
  }
2077
- function parseReaction(answer) {
2855
+ export function parseReaction(answer, state) {
2078
2856
  const value = answer;
2079
2857
  if (!value || typeof value !== 'object' || typeof value.mood !== 'string')
2080
2858
  throw new LivingWorldError('inference-invalid', 'The character answer is malformed');
@@ -2089,11 +2867,16 @@ function parseReaction(answer) {
2089
2867
  ? { topic: request.topic.trim().slice(0, 600), receiverId: request.receiverId,
2090
2868
  priorId: typeof request.priorId === 'string' ? request.priorId : null } : null,
2091
2869
  requestDecision: requestDecision && typeof requestDecision.id === 'string'
2092
- && (requestDecision.status === 'answered' || requestDecision.status === 'refused' || requestDecision.status === 'done')
2870
+ && (requestDecision.status === 'answered' || requestDecision.status === 'accepted' || requestDecision.status === 'refused' || requestDecision.status === 'done')
2093
2871
  ? { id: requestDecision.id, status: requestDecision.status } : null,
2872
+ commitmentDecision: value.commitmentDecision && typeof value.commitmentDecision === 'object'
2873
+ && typeof value.commitmentDecision.id === 'string'
2874
+ && (value.commitmentDecision.status === 'kept' || value.commitmentDecision.status === 'broken')
2875
+ ? { id: value.commitmentDecision.id, status: value.commitmentDecision.status } : null,
2094
2876
  answered: typeof value.answered === 'string' ? value.answered : null,
2095
2877
  act: typeof value.act === 'string' && value.act.trim() !== '' ? value.act.trim().slice(0, 200) : null,
2096
2878
  toIds: Array.isArray(value.toIds) ? value.toIds.filter((id) => typeof id === 'string').slice(0, 4) : [],
2879
+ waitingOnIds: Array.isArray(value.waitingOnIds) ? value.waitingOnIds.filter((id) => typeof id === 'string').slice(0, 4) : [],
2097
2880
  mood: cleanMood(value.mood, 'Present'),
2098
2881
  leaveToPlaceId: typeof value.leaveToPlaceId === 'string' ? value.leaveToPlaceId : null,
2099
2882
  trust: clampInt(value.trust, -20, 20, 0),
@@ -2107,8 +2890,7 @@ function parseReaction(answer) {
2107
2890
  weight: clampInt(value.weight, 1, 10, 3),
2108
2891
  stance: value.stance === 'undecided' || value.stance === 'cooperate' || value.stance === 'refuse'
2109
2892
  || value.stance === 'report' || value.stance === 'avoid' || value.stance === 'confront' ? value.stance : null,
2110
- plan: parsePlanValue(value.plan, 30),
2111
- ballot: parseBallot(value.ballot),
2893
+ plan: parsePlanValue(value.plan, pace(state.calendar, 'defaultActivity')),
2112
2894
  tell: tell && typeof tell.targetId === 'string' && typeof tell.text === 'string' && tell.text.trim() !== '' ? { targetId: tell.targetId, text: tell.text.trim().slice(0, 300) } : null,
2113
2895
  suggestedReplies: Array.isArray(value.suggestedReplies) ? value.suggestedReplies.filter((item) => typeof item === 'string' && item.trim() !== '').map(item => item.trim().slice(0, 120)).slice(0, 3) : [],
2114
2896
  endConversation: value.endConversation === true,
@@ -2119,7 +2901,7 @@ function parseReaction(answer) {
2119
2901
  function reactionFields(state, personId, reaction, cause, trigger, dropped = 0) {
2120
2902
  const person = state.people[personId];
2121
2903
  // Someone who went home or left while deciding says and does nothing here.
2122
- if (person.away || person.departed)
2904
+ if (person.offstage || person.departed)
2123
2905
  return null;
2124
2906
  const actorId = trigger.actorId;
2125
2907
  const present = new Set(peopleAt(state, person.placeId));
@@ -2135,23 +2917,36 @@ function reactionFields(state, personId, reaction, cause, trigger, dropped = 0)
2135
2917
  if ((unheard || again) && reaction.say !== null)
2136
2918
  dropped += 1;
2137
2919
  const say = repeated || unheard || again || blockedByGate(state, personId, 'speak') !== null ? null : reaction.say;
2920
+ let awaiting = null;
2921
+ if (say !== null && addressed.includes(state.playerId)) {
2922
+ const conversation = state.conversations.find(candidate => candidate.endedAt === null
2923
+ && candidate.participantIds.includes(personId) && candidate.participantIds.includes(state.playerId));
2924
+ const lines = conversation === undefined ? [] : [...conversation.lines].sort((left, right) => left.seq - right.seq);
2925
+ const last = lines.filter(line => line.speakerId === state.playerId && line.toIds.includes(personId)).at(-1);
2926
+ if (last !== undefined && !lines.some(line => line.seq > last.seq && line.speakerId === personId && line.toIds.includes(state.playerId)))
2927
+ awaiting = last.seq;
2928
+ }
2138
2929
  if (say !== null)
2139
2930
  effects.push({ kind: 'say', personId, text: say, toIds: addressed });
2140
2931
  if (say !== null && reminding && prior && addressed.includes(prior.receiverId))
2141
2932
  effects.push({ kind: 'request.remind', requestId: prior.id });
2933
+ if (reaction.requestDecision) {
2934
+ const request = state.requests.find(item => item.id === reaction.requestDecision.id);
2935
+ if (request && request.status === 'open')
2936
+ effects.push({ kind: 'request.update', requestId: request.id,
2937
+ status: (reaction.requestDecision.status === 'answered') ? 'accepted' : reaction.requestDecision.status });
2938
+ }
2142
2939
  if (say !== null && reaction.request && !repeated && !reminding && addressed.includes(reaction.request.receiverId)) {
2143
2940
  effects.push({ kind: 'request.open', requestId: generatedId(state.engine, 'request', [cause.seq, personId]), senderId: personId,
2144
2941
  receiverId: reaction.request.receiverId, topic: reaction.request.topic });
2145
2942
  }
2146
- if (reaction.requestDecision)
2147
- effects.push({ kind: 'request.update', requestId: reaction.requestDecision.id,
2148
- status: reaction.requestDecision.status });
2149
- const voted = ballotEffects(state, personId, reaction.ballot, new Set(cause.thingIds ?? []));
2150
- effects.push(...voted);
2943
+ if (reaction.commitmentDecision)
2944
+ effects.push({ kind: 'commitment.update', commitmentId: reaction.commitmentDecision.id,
2945
+ personId, status: reaction.commitmentDecision.status });
2151
2946
  // Someone who hears their own question answered keeps it settled, with the words that settled it.
2152
2947
  const asked = reaction.answered ? state.requests.find(request => request.id === reaction.answered) : undefined;
2153
2948
  if (asked && asked.senderId === personId && asked.receiverId === actorId && asked.status === 'open' && trigger.kind === 'speech') {
2154
- effects.push({ kind: 'request.update', requestId: asked.id, status: 'answered', answer: trigger.text.slice(0, 2000) });
2949
+ effects.push({ kind: 'request.update', requestId: asked.id, status: ('accepted'), answer: trigger.text.slice(0, 2000) });
2155
2950
  }
2156
2951
  const mood = reaction.mood;
2157
2952
  if (mood !== person.mood)
@@ -2187,7 +2982,8 @@ function reactionFields(state, personId, reaction, cause, trigger, dropped = 0)
2187
2982
  effects.push({ kind: 'memory', personId,
2188
2983
  text: cause.observed ?? cause.summary, importance: Math.max(reaction.weight, SHOCK_IMPORTANCE), participantIds: cause.witnessIds.filter(id => id !== personId) });
2189
2984
  }
2190
- if (reaction.plan && (reaction.plan.placeId === null || state.places[reaction.plan.placeId]) && (reaction.plan.targetId === null || state.people[reaction.plan.targetId])) {
2985
+ if (reaction.plan && (reaction.plan.placeId === null || (state.places[reaction.plan.placeId] !== undefined && knowsPlace(state, person, reaction.plan.placeId)))
2986
+ && (reaction.plan.targetId === null || state.people[reaction.plan.targetId])) {
2191
2987
  // Restating a pending plan for the same place and person does not put it off.
2192
2988
  const pending = person.plan;
2193
2989
  const restated = pending !== null && (pending.placeId !== null || pending.targetId !== null)
@@ -2196,8 +2992,8 @@ function reactionFields(state, personId, reaction, cause, trigger, dropped = 0)
2196
2992
  // The plan's id comes from the reaction's own event, so it never repeats an earlier plan's.
2197
2993
  effects.push(...planEffects(state, personId, restated ? { ...reaction.plan, inMinutes: pending.dueAt - state.clock } : reaction.plan, state.revision + 1));
2198
2994
  }
2199
- if (shocked && !state.schedule.some(item => item.personId === personId && isDecision(item) && item.at <= state.clock + SHOCK_PLAN_DELAY_MINUTES)) {
2200
- effects.push({ kind: 'schedule', scheduledId: generatedId(state.engine, 'shock', [cause.seq, personId]), personId, inMinutes: SHOCK_PLAN_DELAY_MINUTES, intent: `${say === null ? 'Decide what to do about this' : 'Decide what to do now, beyond what you said, about this'}: ${observedSummary(cause, personId) ?? cause.observed ?? 'what just happened'}`.slice(0, 600), placeId: null, targetId: target, scheduleKind: 'plan', importance: SHOCK_IMPORTANCE });
2995
+ if (shocked && !state.schedule.some(item => item.personId === personId && isDecision(item) && item.at <= state.clock + pace(state.calendar, 'shockPlanDelay'))) {
2996
+ effects.push({ kind: 'schedule', scheduledId: generatedId(state.engine, 'shock', [cause.seq, personId]), personId, inMinutes: pace(state.calendar, 'shockPlanDelay'), intent: `${say === null ? phrase('decision.this') : phrase('decision.beyondSaid')}: ${observedSummary(cause, personId) ?? cause.observed ?? phrase('decision.whatHappened')}`.slice(0, 600), placeId: null, targetId: target, scheduleKind: 'plan', importance: SHOCK_IMPORTANCE });
2201
2997
  }
2202
2998
  // Passing news on: said now to someone here, sent to an absent player, or carried as an errand to an absent character.
2203
2999
  const told = [];
@@ -2208,7 +3004,7 @@ function reactionFields(state, personId, reaction, cause, trigger, dropped = 0)
2208
3004
  const tellHere = tellTarget !== undefined && isHere(state, tellTarget.id, person.placeId);
2209
3005
  const tellBlocked = tellTarget !== undefined && (tellHere ? gaggedSpeech : tellTarget.isPlayer ? gaggedMessage : gaggedSpeech);
2210
3006
  // Someone away is told nothing by mouth until they are back.
2211
- if (reaction.tell && tellTarget && !tellTarget.incapacitated && !tellBlocked && (tellHere || tellTarget.isPlayer || tellTarget.away === undefined)) {
3007
+ if (reaction.tell && tellTarget && !tellTarget.incapacitated && !tellBlocked && (tellHere || tellTarget.isPlayer || tellTarget.offstage === undefined)) {
2212
3008
  if (tellHere) {
2213
3009
  if (say === null || !addressed.includes(tellTarget.id)) {
2214
3010
  effects.push({ kind: 'say', personId, text: reaction.tell.text, toIds: [tellTarget.id] });
@@ -2221,7 +3017,7 @@ function reactionFields(state, personId, reaction, cause, trigger, dropped = 0)
2221
3017
  told.push(tellTarget.name);
2222
3018
  }
2223
3019
  else if (!state.schedule.some(item => item.personId === personId && item.kind === 'errand')) {
2224
- effects.push({ kind: 'schedule', scheduledId: generatedId(state.engine, 'errand', [cause.seq, personId]), personId, inMinutes: ERRAND_DELAY_MINUTES, intent: reaction.tell.text, placeId: null, targetId: tellTarget.id, scheduleKind: 'errand' });
3020
+ effects.push({ kind: 'schedule', scheduledId: generatedId(state.engine, 'errand', [cause.seq, personId]), personId, inMinutes: pace(state.calendar, 'errandDelay'), intent: reaction.tell.text, placeId: null, targetId: tellTarget.id, scheduleKind: 'errand' });
2225
3021
  }
2226
3022
  }
2227
3023
  if (reaction.endConversation && say === null) {
@@ -2229,39 +3025,39 @@ function reactionFields(state, personId, reaction, cause, trigger, dropped = 0)
2229
3025
  if (conversation)
2230
3026
  effects.push({ kind: 'conversation.end', conversationId: conversation.id });
2231
3027
  }
2232
- let minutes = say === null && told.length === 0 ? 0 : SPEECH_MINUTES;
3028
+ let minutes = say === null && told.length === 0 ? 0 : pace(state.calendar, 'speech');
2233
3029
  const way = reaction.leaveToPlaceId !== null && reaction.leaveToPlaceId !== person.placeId ? travelPath(state, person.placeId, reaction.leaveToPlaceId) : null;
2234
- const leaving = !heldHere(state, personId) && !blockedByGate(state, personId, 'move') && way !== null;
3030
+ const leaving = !heldHere(state, personId) && !blockedByGate(state, personId, 'move') && way !== null
3031
+ && (say !== null || state.clockRate === null || liveExchange(state, personId) === null);
2235
3032
  if (leaving) {
2236
3033
  effects.push({ kind: 'move', personId, placeId: reaction.leaveToPlaceId });
2237
- minutes += TRAVEL_MINUTES_PER_HOP;
3034
+ minutes += travelCost(state, way);
2238
3035
  }
2239
3036
  // A reaction whose every change was left out still leaves a quiet record of how much was left out.
2240
3037
  const holdsBack = (count) => count === 0 ? null : {
2241
- kind: 'reaction', actorId: personId, placeId: person.placeId, summary: `${person.name} holds back`.slice(0, 2000), narration: null, outcome: null,
3038
+ kind: 'reaction', actorId: personId, placeId: person.placeId, summary: phrase('reaction.holdsBack', { name: person.name }).slice(0, 2000), narration: null, outcome: null,
2242
3039
  minutes: 0, effects: [], causeSeq: cause.seq, importance: 1, suggestions: [], ...quiet, droppedEffects: count,
2243
3040
  };
2244
3041
  if (effects.length === 0)
2245
3042
  return holdsBack(dropped);
2246
3043
  // A reaction with nothing said, told or done is inward: its record keeps the mood, and nobody sees it.
2247
3044
  const spoken = [
2248
- ...(say === null ? [] : [`says: "${say}"`]),
2249
- ...(told.length === 0 ? [] : [`tells ${told.join(', ')}: "${reaction.tell.text}"`]),
3045
+ ...(say === null ? [] : [phrase('reaction.says', { text: say })]),
3046
+ ...(told.length === 0 ? [] : [phrase('reaction.tells', { to: told.join(', '), text: reaction.tell.text })]),
2250
3047
  ];
2251
- const outward = [...spoken, ...voted.map(effect => effect.kind === 'ballot' ? `votes ${effect.choice} on ${state.entities[effect.entityId].name}` : ''),
2252
- ...(leaving ? [`leaves for ${state.places[reaction.leaveToPlaceId].name}`] : [])];
3048
+ const outward = [...spoken, ...(leaving ? [phrase('reaction.leavesFor', { place: state.places[reaction.leaveToPlaceId].name })] : [])];
2253
3049
  const fields = {
2254
3050
  kind: 'reaction', actorId: personId, placeId: person.placeId,
2255
- summary: `${person.name} ${outward.length > 0 ? outward.join(' and ') : `reacts (${mood})`}`.slice(0, 2000), narration: null, outcome: null, minutes, effects,
3051
+ summary: `${person.name} ${outward.length > 0 ? outward.join(' and ') : phrase('reaction.reacts', { mood })}`.slice(0, 2000), narration: null, outcome: null, minutes, effects,
2256
3052
  ...(outward.length > 0 ? {} : { perceivedBy: [] }),
2257
3053
  // Onlookers see only the first room they head for, not where they are going.
2258
- ...(leaving ? { observed: `${person.name} ${[...spoken, `leaves toward ${firstRoom(state, way)}`].join(' and ')}`.slice(0, 2000) } : {}),
2259
- causeSeq: cause.seq, importance: Math.max(2, Math.min(10, Math.max(cause.importance - 1, reaction.weight - 1))),
3054
+ ...(leaving ? { observed: `${person.name} ${[...spoken, phrase('reaction.leavesFor', { place: state.places[reaction.leaveToPlaceId].name })].join(' and ')}`.slice(0, 2000) } : {}),
3055
+ causeSeq: awaiting ?? cause.seq, importance: Math.max(2, Math.min(10, Math.max(cause.importance - 1, reaction.weight - 1))),
2260
3056
  suggestions: addressed.includes(state.playerId) ? reaction.suggestedReplies : [], ...quiet,
2261
3057
  ...(dropped > 0 ? { droppedEffects: dropped } : {}),
2262
3058
  };
2263
3059
  try {
2264
- applyLivingEvent(state, { seq: state.revision + 1, at: state.clock, witnessIds: witnessesFor(state, fields), nearbyIds: nearbyFor(state, fields), ...fields });
3060
+ applyLivingEvent(state, { seq: state.revision + 1, at: state.clock, witnessIds: witnessesFor(state, fields), nearbyIds: nearbyFor(state, fields), ...fields, channel: null });
2265
3061
  return fields;
2266
3062
  }
2267
3063
  catch (error) {
@@ -2270,16 +3066,12 @@ function reactionFields(state, personId, reaction, cause, trigger, dropped = 0)
2270
3066
  // Keep what the reducer accepts: the spoken line and the mood, and record what was left out.
2271
3067
  const safe = effects.filter(effect => effect.kind === 'say' || effect.kind === 'mood');
2272
3068
  const { perceivedBy: _inward, observed: _leaving, ...outwardFields } = fields;
2273
- return safe.length === 0 ? holdsBack(dropped + effects.length) : { ...outwardFields, effects: safe, minutes: say === null ? 0 : SPEECH_MINUTES,
3069
+ return safe.length === 0 ? holdsBack(dropped + effects.length) : { ...outwardFields, effects: safe, minutes: say === null ? 0 : pace(state.calendar, 'speech'),
2274
3070
  summary: (say === null ? `${person.name} reacts (${mood})` : `${person.name} says: "${say}"`).slice(0, 2000),
2275
3071
  ...(say === null ? { perceivedBy: [] } : {}), ...(dropped + effects.length - safe.length > 0 ? { droppedEffects: dropped + effects.length - safe.length } : {}) };
2276
3072
  }
2277
- }
2278
- // What onlookers see of someone setting off is the first room on their way, never where or why they go;
2279
- // the player's map keeps the same room as where they were last seen heading.
2280
- function firstRoom(state, path) {
2281
- const next = path[1] ?? path[0];
2282
- return state.places[next]?.name ?? next;
3073
+ // What onlookers see of someone setting off is the first room on their way, never where or why they go;
3074
+ // the player's map keeps the same room as where they were last seen heading.
2283
3075
  }
2284
3076
  // A pending decision about someone's serious act is a plan item that carries that person's id and
2285
3077
  // the act's importance. Routine plans replace one another but never a pending decision.
@@ -2289,24 +3081,25 @@ function isDecision(item) {
2289
3081
  return item.kind === 'plan' && item.importance >= SHOCK_IMPORTANCE
2290
3082
  && (item.targetId !== null || item.id.startsWith('nearby-shock-') || item.id.startsWith('shock-') || item.id.startsWith('vote-'));
2291
3083
  }
2292
- function planEffects(state, personId, plan, seq, suffix = '') {
3084
+ function planEffects(state, personId, plan, seq, suffix = '', importance = ROUTINE_PLAN_IMPORTANCE, selfPlanned = true, waitingForExchange = false) {
2293
3085
  const existing = state.schedule.filter(item => item.personId === personId && item.kind === 'plan' && !isDecision(item));
2294
3086
  return [
2295
3087
  ...existing.map((item) => ({ kind: 'unschedule', scheduledId: item.id })),
2296
3088
  { kind: 'plan', personId, plan: { intent: plan.intent, ...(plan.seen ? { seen: plan.seen } : {}), placeId: plan.placeId, targetId: plan.targetId, dueAt: state.clock + plan.inMinutes } },
2297
- { kind: 'schedule', scheduledId: generatedId(state.engine, 'plan', [seq, personId, suffix], `plan-${seq}-${personId}${suffix}`, true), personId, inMinutes: plan.inMinutes, intent: plan.intent, placeId: plan.placeId, targetId: plan.targetId, scheduleKind: 'plan', importance: ROUTINE_PLAN_IMPORTANCE,
2298
- ...(state.engine >= BOUNDED_IDENTIFIERS_ENGINE && suffix === '-again' ? { replanned: true } : {}) },
3089
+ { kind: 'schedule', scheduledId: generatedId(state.engine, 'plan', [seq, personId, suffix], `plan-${seq}-${personId}${suffix}`, true), personId, inMinutes: plan.inMinutes, intent: plan.intent, placeId: plan.placeId, targetId: plan.targetId, scheduleKind: 'plan', importance,
3090
+ ...((suffix === '-again') ? { replanned: true } : {}), ...(selfPlanned ? { selfPlanned: true } : {}),
3091
+ ...(waitingForExchange ? { waitingForExchange: true } : {}) },
2299
3092
  ];
2300
3093
  }
2301
3094
  // A shock sets routine business aside: the witness decides about it a few minutes later.
2302
- function shockPlanEffects(state, personId, scheduledId, intent, inMinutes, actorId) {
3095
+ function shockPlanEffects(state, personId, scheduledId, intent, inMinutes, actorId, decisionsOnly = false) {
2303
3096
  const urgent = state.schedule.find(item => item.personId === personId
2304
- && item.at <= state.clock + inMinutes && item.importance >= SHOCK_IMPORTANCE);
3097
+ && (!decisionsOnly || isDecision(item)) && item.at <= state.clock + inMinutes && item.importance >= SHOCK_IMPORTANCE);
2305
3098
  if (urgent)
2306
3099
  return [];
2307
3100
  return [
2308
3101
  ...state.schedule.filter(item => item.personId === personId && item.kind === 'plan' && !isDecision(item)).map((item) => ({ kind: 'unschedule', scheduledId: item.id })),
2309
- { kind: 'plan', personId, plan: { intent, placeId: null, targetId: actorId, dueAt: state.clock + inMinutes } },
3102
+ { kind: 'plan', personId, plan: { intent, placeId: null, targetId: actorId, dueAt: state.clock + inMinutes }, deciding: true },
2310
3103
  { kind: 'schedule', scheduledId, personId, inMinutes, intent, placeId: null, targetId: actorId, scheduleKind: 'plan', importance: SHOCK_IMPORTANCE },
2311
3104
  ];
2312
3105
  }
@@ -2323,7 +3116,7 @@ async function replyBetween(session, speakerId, listenerId, cause, text) {
2323
3116
  await react(session, [listenerId], cause, { kind: 'speech', actorId: speakerId, text, narration: null }, 'reply', true);
2324
3117
  }
2325
3118
  // ---- Scheduled activity -------------------------------------------------------
2326
- async function settleDue(session) {
3119
+ async function settleDue(session, allowReactions = true) {
2327
3120
  let handled = 0;
2328
3121
  const attempted = new Set();
2329
3122
  const recovered = new Set();
@@ -2331,14 +3124,15 @@ async function settleDue(session) {
2331
3124
  const state = session.state;
2332
3125
  // The schedule is ordered by time, so the due items are its head.
2333
3126
  const ready = [];
2334
- for (const list of [state.schedule, state.meterSchedule])
3127
+ for (const list of [state.schedule, state.predictions.items]) {
2335
3128
  for (const item of list) {
2336
3129
  if (item.at > state.clock)
2337
3130
  break;
2338
3131
  if (!attempted.has(item.id) && predictionReady(state, item))
2339
3132
  ready.push(item);
2340
3133
  }
2341
- ready.sort((left, right) => right.importance - left.importance || left.at - right.at || left.id.localeCompare(right.id));
3134
+ }
3135
+ ready.sort((left, right) => right.importance - left.importance || left.at - right.at || left.sourceSeq - right.sourceSeq);
2342
3136
  // A person whose typed cause no longer holds recovers with an event where they are, whether or
2343
3137
  // not anyone is with them; a command loads the surroundings of everyone who cannot act.
2344
3138
  const recovering = Object.values(state.people).find(person => person.incapacitatedBy !== undefined && !recovered.has(person.id)
@@ -2349,6 +3143,13 @@ async function settleDue(session) {
2349
3143
  effects: [], causeSeq: null, importance: 2, suggestions: [], ...quiet });
2350
3144
  continue;
2351
3145
  }
3146
+ for (const item of [...ready]) {
3147
+ if (!isChoiceTurn(state, item) || item.personId === null)
3148
+ continue;
3149
+ const offered = openChoices(state, item.personId).choices?.some(choice => choice.id === item.targetId) === true;
3150
+ if (!offered || state.people[item.personId]?.isPlayer)
3151
+ ready.splice(ready.indexOf(item), 1);
3152
+ }
2352
3153
  const abandoned = ready.find(item => ownerCannotAct(state, item));
2353
3154
  if (abandoned) {
2354
3155
  abandon(session, abandoned);
@@ -2356,12 +3157,27 @@ async function settleDue(session) {
2356
3157
  }
2357
3158
  const modelAllowed = handled < MAX_DUE_ITEMS_PER_STEP && session.canSpend();
2358
3159
  const due = modelAllowed
2359
- ? handled === 0 ? ready.find(item => item.kind === 'world') ?? ready[0]
2360
- : ready.find(item => item.kind !== 'world') ?? ready.find(item => item.kind === 'world')
2361
- : ready.find(item => item.kind === 'arrive' || item.kind === 'errand' || item.kind === 'deliver' || item.kind === 'back' || item.kind === 'count');
3160
+ ? ready.find(item => item.kind === scheduledKindSchema.enum.react)
3161
+ ?? (handled === 0 ? ready.find(item => item.kind === 'world') ?? ready[0]
3162
+ : ready.find(item => item.kind !== 'world') ?? ready.find(item => item.kind === 'world'))
3163
+ : ready.find(item => item.kind === 'arrive' || item.kind === 'errand' || item.kind === 'deliver' || item.kind === 'onstage');
2362
3164
  if (!due)
2363
3165
  break;
2364
- const needsModel = due.kind === 'reply' || due.kind === 'plan' || due.kind === 'world' || due.kind === 'finish';
3166
+ if (!allowReactions && due.kind === scheduledKindSchema.enum.react) {
3167
+ attempted.add(due.id);
3168
+ continue;
3169
+ }
3170
+ if (due.kind === scheduledKindSchema.enum.react && due.sourceSeq > session.startedAtRevision) {
3171
+ attempted.add(due.id);
3172
+ continue;
3173
+ }
3174
+ if (due.law !== undefined) {
3175
+ session.commit({ kind: 'world', actorId: null, placeId: due.placeId, summary: due.intent, narration: null, outcome: null, minutes: 0,
3176
+ effects: [{ kind: 'unschedule', scheduledId: due.id }], causeSeq: due.sourceSeq || null, importance: due.importance, suggestions: [], ...quiet, lawSeeds: [due.law] });
3177
+ continue;
3178
+ }
3179
+ const needsModel = due.kind === 'reply' || due.kind === 'answer' || due.kind === 'plan' || due.kind === 'world' || due.kind === 'finish'
3180
+ || due.kind === scheduledKindSchema.enum.react;
2365
3181
  if (needsModel)
2366
3182
  handled += 1;
2367
3183
  // An item the model could not answer stays due, but does not block other ready work.
@@ -2373,7 +3189,8 @@ function ownerCannotAct(state, item) {
2373
3189
  const owner = item.personId === null ? null : state.people[item.personId];
2374
3190
  // Someone away decides nothing until they are back; a plan or errand that came due meanwhile is set aside.
2375
3191
  return item.personId !== null && (!owner || owner.incapacitated || owner.isPlayer || owner.departed !== undefined
2376
- || owner.away !== undefined && (item.kind === 'plan' || item.kind === 'arrive' || item.kind === 'errand'));
3192
+ || owner.offstage !== undefined && (item.kind === 'plan' || item.kind === 'arrive' || item.kind === 'errand' || item.kind === 'answer'
3193
+ || item.kind === scheduledKindSchema.enum.react));
2377
3194
  }
2378
3195
  // The event cites the complete scheduled intent by sourceSeq; only its display summary is shortened.
2379
3196
  function intentSummary(prefix, intent, suffix) {
@@ -2387,55 +3204,68 @@ function intentSummary(prefix, intent, suffix) {
2387
3204
  return prefix + excerpt + '…' + suffix;
2388
3205
  }
2389
3206
  function abandon(session, item) {
2390
- session.commit({ kind: 'plan', actorId: null, placeId: item.placeId, summary: intentSummary('The appointment to ', item.intent, ' cannot proceed because its owner cannot act.'),
3207
+ session.commit({ kind: 'plan', actorId: null, placeId: item.placeId, summary: intentSummary(phrase('appointment.prefix'), item.intent, phrase('appointment.suffix')),
2391
3208
  narration: null, outcome: null, minutes: 0, effects: [{ kind: 'unschedule', scheduledId: item.id }], causeSeq: item.sourceSeq || null, importance: 2, suggestions: [], ...quiet });
2392
3209
  }
2393
3210
  function dispatchItem(session, due) {
2394
3211
  switch (due.kind) {
2395
3212
  case 'reply': return answerMessage(session, due);
3213
+ case 'answer': return answerInPerson(session, due);
2396
3214
  case 'arrive': return arriveAndSpeak(session, due);
2397
3215
  case 'errand': return runErrand(session, due);
2398
3216
  case 'world': return worldFollowUp(session, due);
2399
- case 'plan': return carryOutPlan(session, due, true);
3217
+ case 'plan': {
3218
+ const person = session.state.people[due.personId];
3219
+ if (person?.incidental)
3220
+ return renewIncidental(session, due);
3221
+ // A routine activity whose situation has not changed carries on; the timer alone is no reason to decide.
3222
+ if (routinePlanUnchanged(session.state, due))
3223
+ return carryOnPlan(session, due);
3224
+ return carryOutPlan(session, due, true);
3225
+ }
2400
3226
  case 'deliver': return deliverMessage(session, due);
2401
3227
  case 'finish': return finishAct(session, due);
2402
- case 'back': return comeBack(session, due);
2403
- case 'count': return countVote(session, due);
3228
+ case 'onstage': return comeBack(session, due);
3229
+ case 'react': return scheduledReaction(session, due);
2404
3230
  }
2405
3231
  }
2406
- // A vote opens or is counted at its written time, with no model. Its opening gives each member who has
2407
- // not voted a turn to decide; at its close the ballots cast decide the result. Both are news everywhere.
2408
- async function countVote(session, due) {
3232
+ async function scheduledReaction(session, due) {
2409
3233
  const state = session.state;
2410
- const decision = due.count ? state.entities[due.count.entityId] : undefined;
2411
- const done = [{ kind: 'unschedule', scheduledId: due.id }];
2412
- const base = { actorId: null, placeId: decision?.placeId ?? due.placeId, narration: null, outcome: null, minutes: 0, causeSeq: due.sourceSeq || null, suggestions: [], ...quiet };
2413
- if (!decision || decision.members === undefined || decision.result !== undefined) {
2414
- session.commit({ kind: 'world', ...base, summary: intentSummary('', due.intent, ': nothing left to count.'), effects: done, importance: 1 });
3234
+ const person = state.people[due.personId];
3235
+ const cause = state.events.find(event => event.seq === due.sourceSeq);
3236
+ const giveUp = () => {
3237
+ if (session.state.schedule.some(item => item.id === due.id))
3238
+ session.commit({ kind: 'plan', actorId: person?.id ?? null, placeId: person?.placeId ?? null,
3239
+ summary: phrase('reaction.holdsBack', { name: person?.name ?? phrase('detail.someone') }), narration: null, outcome: null, ...instant,
3240
+ effects: [{ kind: 'unschedule', scheduledId: due.id }], causeSeq: due.sourceSeq || null, importance: 1, suggestions: [], ...quiet, perceivedBy: [] });
2415
3241
  return true;
3242
+ };
3243
+ if (!person || cause === undefined || person.incapacitated || person.departed !== undefined || person.offstage !== undefined
3244
+ || !cause.witnessIds.includes(person.id))
3245
+ return giveUp();
3246
+ const answering = cause.causeSeq !== null;
3247
+ if (answering)
3248
+ session.answeringActs += 1;
3249
+ try {
3250
+ await react(session, [person.id], cause, { kind: 'attempt', actorId: cause.actorId ?? state.playerId, text: due.intent, narration: null }, 'reaction', false);
2416
3251
  }
2417
- if (due.count.opens) {
2418
- const question = String(decision.properties.question?.value ?? decision.name).slice(0, 300);
2419
- const voters = decision.members.map(id => state.people[id]).filter((person) => person !== undefined
2420
- && !person.isPlayer && person.departed === undefined && decision.ballots?.[person.id] === undefined);
2421
- session.commit({ kind: 'world', ...base, summary: `Voting opens on ${decision.name}.`, observed: `Voting opens on ${decision.name}.`, importance: 4,
2422
- reach: 'everywhere', notice: `Voting opens on ${decision.name}.`,
2423
- effects: [...done, ...voters.map((person, index) => ({ kind: 'schedule', scheduledId: generatedId(state.engine, 'vote', [state.revision + 1, person.id], `vote-${state.revision + 1}-${person.id}`.slice(0, 64)), personId: person.id,
2424
- inMinutes: 1 + index, intent: `Cast your vote on ${decision.name}: ${question}`.slice(0, MAX_LINE), placeId: null, targetId: null, scheduleKind: 'plan', importance: PROMISE_IMPORTANCE }))] });
2425
- return true;
3252
+ catch (error) {
3253
+ if (error instanceof LivingWorldError && RETRYABLE[error.code] === true)
3254
+ return false;
3255
+ throw error;
2426
3256
  }
2427
- const result = countResult(decision);
2428
- session.commit({ kind: 'world', ...base, summary: `The votes on ${decision.name} are counted: ${result}.`, observed: `The votes on ${decision.name} are counted: ${result}.`, importance: 6,
2429
- reach: 'everywhere', notice: `The votes on ${decision.name} are counted: ${result}.`,
2430
- effects: [...done, { kind: 'decision.close', entityId: decision.id, result }] });
2431
- return true;
3257
+ finally {
3258
+ if (answering)
3259
+ session.answeringActs -= 1;
3260
+ }
3261
+ return giveUp();
2432
3262
  }
2433
3263
  // Someone away comes back to where they left from when their time away is up; what to do next
2434
3264
  // they decide there.
2435
3265
  async function comeBack(session, due) {
2436
3266
  const person = session.state.people[due.personId];
2437
3267
  session.commit({ kind: 'move', actorId: person.id, placeId: person.placeId, summary: `${person.name} comes back`, narration: null, outcome: null, minutes: 0,
2438
- effects: [{ kind: 'unschedule', scheduledId: due.id }, ...(person.away ? [{ kind: 'person.back', personId: person.id }] : []), { kind: 'plan', personId: person.id, plan: null }],
3268
+ effects: [{ kind: 'unschedule', scheduledId: due.id }, ...(person.offstage ? [{ kind: 'person.onstage', personId: person.id }] : []), { kind: 'plan', personId: person.id, plan: null }],
2439
3269
  causeSeq: due.sourceSeq || null, importance: 1, suggestions: [], ...quiet, observed: `${person.name} comes in.` });
2440
3270
  return true;
2441
3271
  }
@@ -2444,6 +3274,11 @@ async function settleItem(session, due) {
2444
3274
  abandon(session, due);
2445
3275
  return true;
2446
3276
  }
3277
+ if (due.law !== undefined) {
3278
+ session.commit({ kind: 'world', actorId: null, placeId: due.placeId, summary: due.intent, narration: null, outcome: null, minutes: 0,
3279
+ effects: [{ kind: 'unschedule', scheduledId: due.id }], causeSeq: due.sourceSeq || null, importance: due.importance, suggestions: [], ...quiet, lawSeeds: [due.law] });
3280
+ return true;
3281
+ }
2447
3282
  return dispatchItem(session, due);
2448
3283
  }
2449
3284
  // A character who walked over to say something says it on arrival, no model needed.
@@ -2456,17 +3291,17 @@ async function arriveAndSpeak(session, due) {
2456
3291
  if (target && (unansweredSince(state, person.id, target.id) !== null || saidAlready(state, person.id, due.intent))) {
2457
3292
  // Someone who has left this person's last lines unanswered, or already heard these words, is not told it again on arrival.
2458
3293
  session.commit({
2459
- kind: 'plan', actorId: person.id, placeId: person.placeId, summary: `${person.name} leaves it unsaid: ${target.name} ${unansweredSince(state, person.id, target.id) !== null ? 'has not answered' : 'has heard it already'}`, narration: null, outcome: null, minutes: 0,
2460
- effects: [{ kind: 'unschedule', scheduledId: due.id }, ...(session.live() ? planEffects({ ...state, schedule: state.schedule.filter(item => item.id !== due.id) }, person.id, { intent: 'Carry on with the day', placeId: null, targetId: null, inMinutes: DEFAULT_ACTIVITY_MINUTES }, state.revision + 1) : [{ kind: 'plan', personId: person.id, plan: null }])],
3294
+ kind: 'plan', actorId: person.id, placeId: person.placeId, summary: `${person.name} leaves it unsaid: ${target.name} ${unansweredSince(state, person.id, target.id) !== null ? phrase('reply.notAnswered') : phrase('reply.heardAlready')}`, narration: null, outcome: null, minutes: 0,
3295
+ effects: [{ kind: 'unschedule', scheduledId: due.id }, ...(session.live() ? planEffects({ ...state, schedule: state.schedule.filter(item => item.id !== due.id) }, person.id, { intent: phrase('plan.carryOn'), placeId: null, targetId: null, inMinutes: pace(state.calendar, 'defaultActivity') }, state.revision + 1) : [{ kind: 'plan', personId: person.id, plan: null }])],
2461
3296
  causeSeq: cause, importance: 1, suggestions: [], ...quiet, droppedEffects: 1,
2462
3297
  });
2463
3298
  return true;
2464
3299
  }
2465
3300
  if (target && isHere(state, target.id, person.placeId) && !target.incapacitated && blockedByGate(state, person.id, 'speak') === null) {
2466
3301
  const event = session.commit({
2467
- kind: 'reaction', actorId: person.id, placeId: person.placeId, summary: `${person.name} says to ${target.name}: "${due.intent}"`.slice(0, 2000), narration: null, outcome: null, minutes: SPEECH_MINUTES,
3302
+ kind: 'reaction', actorId: person.id, placeId: person.placeId, summary: phrase('act.saysTo', { name: person.name, target: target.name, text: due.intent }).slice(0, 2000), narration: null, outcome: null, minutes: pace(session.state.calendar, 'speech'),
2468
3303
  effects: [{ kind: 'unschedule', scheduledId: due.id }, { kind: 'say', personId: person.id, text: due.intent, toIds: [target.id] },
2469
- ...(session.live() ? planEffects({ ...state, schedule: state.schedule.filter(item => item.id !== due.id) }, person.id, { intent: `Talk with ${target.name}`, seen: `talking with ${target.name}`, placeId: null, targetId: target.id, inMinutes: DEFAULT_ACTIVITY_MINUTES }, state.revision + 1)
3304
+ ...(session.live() ? planEffects({ ...state, schedule: state.schedule.filter(item => item.id !== due.id) }, person.id, { intent: phrase('plan.talkWith', { name: target.name }), seen: phrase('plan.talkingWith', { name: target.name }), placeId: null, targetId: target.id, inMinutes: pace(state.calendar, 'defaultActivity') }, state.revision + 1)
2470
3305
  : [{ kind: 'plan', personId: person.id, plan: null }])],
2471
3306
  causeSeq: cause, importance: 3, suggestions: [], ...quiet,
2472
3307
  });
@@ -2475,8 +3310,8 @@ async function arriveAndSpeak(session, due) {
2475
3310
  }
2476
3311
  const seq = state.revision + 1;
2477
3312
  session.commit({
2478
- kind: 'plan', actorId: person.id, placeId: person.placeId, summary: `${person.name} arrives, but ${target?.name ?? 'the person they came for'} is not here`, narration: null, outcome: null, minutes: 0,
2479
- effects: [{ kind: 'unschedule', scheduledId: due.id }, ...planEffects({ ...state, schedule: state.schedule.filter(item => item.id !== due.id) }, person.id, { intent: `Find ${target?.name ?? 'someone'} and say: ${due.intent}`.slice(0, 300), placeId: null, targetId: target?.id ?? null, inMinutes: 30 }, seq)],
3313
+ kind: 'plan', actorId: person.id, placeId: person.placeId, summary: `${person.name} arrives, but ${target?.name ?? phrase('plan.cameFor')} is not here`, narration: null, outcome: null, minutes: 0,
3314
+ effects: [{ kind: 'unschedule', scheduledId: due.id }, ...planEffects({ ...state, schedule: state.schedule.filter(item => item.id !== due.id) }, person.id, { intent: phrase('plan.findAndSay', { name: target?.name ?? 'someone', text: due.intent }).slice(0, 300), placeId: null, targetId: target?.id ?? null, inMinutes: pace(state.calendar, 'defaultActivity') }, seq)],
2480
3315
  causeSeq: cause, importance: 1, suggestions: [], ...quiet,
2481
3316
  });
2482
3317
  return true;
@@ -2488,28 +3323,28 @@ async function runErrand(session, due) {
2488
3323
  const target = due.targetId ? state.people[due.targetId] : undefined;
2489
3324
  const cause = due.sourceSeq || null;
2490
3325
  const drop = (why) => session.commit({
2491
- kind: 'plan', actorId: person.id, placeId: person.placeId, summary: `${person.name} lets it go: ${why}`, narration: null, outcome: null, minutes: 0,
3326
+ kind: 'plan', actorId: person.id, placeId: person.placeId, summary: phrase('plan.letsGo', { name: person.name, why }), narration: null, outcome: null, minutes: 0,
2492
3327
  effects: [{ kind: 'unschedule', scheduledId: due.id }], causeSeq: cause, importance: 1, suggestions: [], ...quiet,
2493
3328
  });
2494
3329
  if (!target || target.incapacitated) {
2495
- drop(`${target?.name ?? 'the person'} cannot be told now`);
3330
+ drop(phrase('plan.cannotBeTold', { name: target?.name ?? phrase('plan.thePerson') }));
2496
3331
  return true;
2497
3332
  }
2498
3333
  if (unansweredSince(state, person.id, target.id) !== null) {
2499
- drop(`${target.name} has not answered`);
3334
+ drop(`${target.name} ${phrase('reply.notAnswered')}`);
2500
3335
  return true;
2501
3336
  }
2502
3337
  if ((heldHere(state, person.id) || blockedByGate(state, person.id, 'move')) && target.placeId !== person.placeId) {
2503
- drop(`${person.name} cannot leave to find ${target.name}`);
3338
+ drop(phrase('plan.cannotLeave', { name: person.name, target: target.name }));
2504
3339
  return true;
2505
3340
  }
2506
3341
  if (blockedByGate(state, person.id, 'speak') !== null) {
2507
- drop(`${person.name} cannot speak now`);
3342
+ drop(phrase('plan.cannotSpeak', { name: person.name }));
2508
3343
  return true;
2509
3344
  }
2510
3345
  if (isHere(state, target.id, person.placeId)) {
2511
3346
  const event = session.commit({
2512
- kind: 'reaction', actorId: person.id, placeId: person.placeId, summary: `${person.name} says to ${target.name}: "${due.intent}"`.slice(0, 2000), narration: null, outcome: null, minutes: SPEECH_MINUTES,
3347
+ kind: 'reaction', actorId: person.id, placeId: person.placeId, summary: phrase('act.saysTo', { name: person.name, target: target.name, text: due.intent }).slice(0, 2000), narration: null, outcome: null, minutes: pace(session.state.calendar, 'speech'),
2513
3348
  effects: [{ kind: 'unschedule', scheduledId: due.id }, { kind: 'say', personId: person.id, text: due.intent, toIds: [target.id] }],
2514
3349
  causeSeq: cause, importance: 3, suggestions: [], ...quiet,
2515
3350
  });
@@ -2518,19 +3353,31 @@ async function runErrand(session, due) {
2518
3353
  }
2519
3354
  const path = travelPath(state, person.placeId, target.placeId);
2520
3355
  if (!path) {
2521
- drop(`there is no way to reach ${target.name}`);
3356
+ drop(phrase('plan.noWay', { name: target.name }));
3357
+ return true;
3358
+ }
3359
+ const exchange = (state.clockRate !== null) ? liveExchange(state, person.id) : null;
3360
+ if (exchange !== null) {
3361
+ const seq = state.revision + 1;
3362
+ const wait = (Math.min(pace(state.calendar, 'exchangeCheck'), Math.max(pace(state.calendar, 'speech'), exchange.lastLineAt + pace(state.calendar, 'exchangeTurn') - state.clock)));
3363
+ session.commit({ kind: 'plan', actorId: person.id, placeId: person.placeId, summary: phrase('plan.waitsToTell', { name: person.name, target: target.name, text: due.intent }).slice(0, 2000), narration: null, outcome: null, minutes: 0,
3364
+ effects: [{ kind: 'unschedule', scheduledId: due.id },
3365
+ { kind: 'schedule', scheduledId: generatedId(state.engine, 'errand', [seq, person.id], `errand-${seq}-${person.id}`, true), personId: person.id,
3366
+ inMinutes: Math.max(pace(state.calendar, 'speech'), wait), intent: due.intent, placeId: due.placeId, targetId: due.targetId,
3367
+ scheduleKind: 'errand', importance: due.importance }],
3368
+ causeSeq: cause, importance: 1, suggestions: [], ...quiet });
2522
3369
  return true;
2523
3370
  }
2524
3371
  const seq = state.revision + 1;
2525
3372
  session.commit({
2526
- kind: 'move', actorId: person.id, placeId: person.placeId, summary: `${person.name} travels to ${state.places[target.placeId].name} to find ${target.name}`, narration: null, outcome: null, minutes: (path.length - 1) * TRAVEL_MINUTES_PER_HOP,
2527
- observed: `${person.name} leaves toward ${firstRoom(state, path)}.`,
3373
+ kind: 'move', actorId: person.id, placeId: person.placeId, summary: phrase('plan.travelsToFind', { name: person.name, place: state.places[target.placeId].name, target: target.name }), narration: null, outcome: null, minutes: travelCost(state, path),
3374
+ observed: `${person.name} leaves for ${state.places[target.placeId].name}.`,
2528
3375
  effects: [
2529
3376
  { kind: 'unschedule', scheduledId: due.id },
2530
3377
  { kind: 'move', personId: person.id, placeId: target.placeId },
2531
3378
  // What to tell them is chosen on arrival, from what is there then.
2532
- ...planEffects({ ...state, schedule: state.schedule.filter(item => item.id !== due.id) }, person.id, { intent: `Tell ${target.name}: ${due.intent}`.slice(0, 300),
2533
- seen: `on the way to ${target.name}`, placeId: target.placeId, targetId: target.id, inMinutes: (path.length - 1) * TRAVEL_MINUTES_PER_HOP }, seq),
3379
+ ...planEffects({ ...state, schedule: state.schedule.filter(item => item.id !== due.id) }, person.id, { intent: phrase('plan.tell', { name: target.name, text: due.intent }).slice(0, 300),
3380
+ seen: `on the way to ${target.name}`, placeId: target.placeId, targetId: target.id, inMinutes: travelCost(state, path) }, seq),
2534
3381
  ],
2535
3382
  causeSeq: cause, importance: 2, suggestions: [], ...quiet,
2536
3383
  });
@@ -2544,12 +3391,11 @@ function nextTime(due) {
2544
3391
  return [];
2545
3392
  const next = due.at + due.everyMinutes * Math.max(1, Math.floor((state.clock - due.at) / due.everyMinutes) + 1);
2546
3393
  return [{ kind: 'schedule', scheduledId: generatedId(state.engine, 'repeat', [due.series ?? due.id, next], `${due.series ?? due.id}-${next}`.slice(0, 64), true),
2547
- personId: null, inMinutes: next - state.clock, intent: due.intent, placeId: due.placeId, targetId: due.targetId, scheduleKind: 'world', importance: due.importance,
3394
+ personId: null, inMinutes: Math.max(pace(state.calendar, 'speech'), next - state.clock), intent: due.intent, placeId: due.placeId, targetId: due.targetId, scheduleKind: 'world', importance: due.importance,
2548
3395
  everyMinutes: due.everyMinutes, series: due.series ?? due.id, ...(due.beat === undefined ? {} : { beat: due.beat }) }];
2549
3396
  };
2550
3397
  }
2551
3398
  // The typed results a world's data gives one of its happenings, as far as the world can take them now:
2552
- // facts that replace their aspect, a problem's new state, money that moves.
2553
3399
  function beatResults(state, placeId, beat) {
2554
3400
  if (!beat?.then)
2555
3401
  return [];
@@ -2557,14 +3403,13 @@ function beatResults(state, placeId, beat) {
2557
3403
  const results = [
2558
3404
  ...(beat.then.facts ?? []).map((fact) => ({ kind: 'fact', add: fact.text, remove: null, aspect: fact.aspect })),
2559
3405
  ...(tension && beat.then.tension ? [{ kind: 'tension.update', tensionId: tension.id, status: beat.then.tension.status ?? tension.status, note: beat.then.tension.summary ?? null }] : []),
2560
- ...(beat.then.transfers ?? []).map((transfer) => ({ kind: 'transfer', ...transfer })),
3406
+ ...(beat.then.shifts ?? []).map((shift) => ({ kind: 'shift', slotId: shift.slot, fromId: shift.fromId, toId: shift.toId, amount: shift.amount })),
2561
3407
  ];
2562
- // Each result is kept only if the world can take it now, such as a cost the money on hand can pay.
2563
- const draft = { kind: 'world', actorId: null, placeId, summary: 'A due happening.', narration: null, outcome: null, minutes: 0, causeSeq: null, importance: 1, suggestions: [], reach: 'here', notice: null, effects: [] };
3408
+ const draft = { kind: 'world', actorId: null, placeId, summary: phrase('happening.due'), narration: null, outcome: null, minutes: 0, causeSeq: null, importance: 1, suggestions: [], reach: 'here', notice: null, effects: [] };
2564
3409
  const kept = [];
2565
3410
  for (const effect of results) {
2566
3411
  try {
2567
- applyLivingEvent(state, { seq: state.revision + 1, at: state.clock, witnessIds: witnessesFor(state, draft), nearbyIds: nearbyFor(state, draft), ...draft, effects: [...kept, effect] });
3412
+ applyLivingEvent(state, { seq: state.revision + 1, at: state.clock, witnessIds: witnessesFor(state, draft), nearbyIds: nearbyFor(state, draft), ...draft, channel: null, effects: [...kept, effect] });
2568
3413
  kept.push(effect);
2569
3414
  }
2570
3415
  catch (error) {
@@ -2575,11 +3420,11 @@ function beatResults(state, placeId, beat) {
2575
3420
  return kept;
2576
3421
  }
2577
3422
  function describeResult(state, effect) {
2578
- const holder = (id) => id === null ? 'outside the world' : state.accounts?.[id]?.name ?? personLabel(state, id);
3423
+ const holder = (id) => id === null ? phrase('world.outside') : state.people[id]?.name ?? state.entities[id]?.name ?? state.places[id]?.name ?? id;
2579
3424
  switch (effect.kind) {
2580
3425
  case 'fact': return effect.add ?? '';
2581
3426
  case 'tension.update': return `${state.tensions.find(tension => tension.id === effect.tensionId)?.title ?? effect.tensionId}: ${effect.note ?? effect.status}`;
2582
- case 'transfer': return `${effect.amount}${state.currency ? ` ${state.currency.name}` : ''} pass from ${holder(effect.fromId)} to ${holder(effect.toId)}`;
3427
+ case 'shift': return `${effect.amount} ${state.units[state.numbers[effect.slotId]?.unit ?? '']?.name ?? effect.slotId} pass from ${holder(effect.fromId)} to ${holder(effect.toId)}`;
2583
3428
  default: return '';
2584
3429
  }
2585
3430
  }
@@ -2588,16 +3433,16 @@ function describeResult(state, effect) {
2588
3433
  async function stallCheck(session, due) {
2589
3434
  const state = session.state;
2590
3435
  const again = nextTime(due);
2591
- const stalled = state.tensions.filter(tension => tension.status === 'open' && state.clock - tension.changedAt >= STALL_MINUTES)
3436
+ const stalled = state.tensions.filter(tension => tension.status === 'open' && state.clock - tension.changedAt >= pace(state.calendar, 'stall'))
2592
3437
  .sort((left, right) => left.changedAt - right.changedAt || left.id.localeCompare(right.id))[0];
2593
3438
  if (stalled === undefined) {
2594
3439
  // The engine's own check is no event in the world: no one sees it.
2595
- session.commit({ kind: 'world', actorId: null, placeId: session.player().placeId, summary: 'No open problem has stood still', narration: null, outcome: null, minutes: 0,
3440
+ session.commit({ kind: 'world', actorId: null, placeId: session.player().placeId, summary: phrase('problem.noneStill'), narration: null, outcome: null, minutes: 0,
2596
3441
  effects: [{ kind: 'unschedule', scheduledId: due.id }, ...again(state)], causeSeq: null, importance: 1, suggestions: [], ...quiet, perceivedBy: [] });
2597
3442
  return true;
2598
3443
  }
2599
3444
  // It goes on where those it concerns are.
2600
- const placeId = stalled.participantIds.map(id => state.people[id]).find(person => person !== undefined && !person.isPlayer && !person.away && !person.departed)?.placeId
3445
+ const placeId = stalled.participantIds.map(id => state.people[id]).find(person => person !== undefined && !person.isPlayer && !person.offstage && !person.departed)?.placeId
2601
3446
  ?? session.player().placeId;
2602
3447
  try {
2603
3448
  await resolve(session, {
@@ -2607,7 +3452,7 @@ async function stallCheck(session, due) {
2607
3452
  trigger: ruling => ({ kind: 'world', actorId: null, text: ruling.observed ?? ruling.narration, narration: ruling.narration }),
2608
3453
  // What the ruling made of it becomes where the problem now stands.
2609
3454
  rulingEffects: (_state, ruling) => ruling.settledTensionId === stalled.id ? [] : [{ kind: 'tension.update', tensionId: stalled.id, status: 'open', note: ruling.record.slice(0, 2000) }],
2610
- movesNoMoney: true,
3455
+ movesNoNumbers: true,
2611
3456
  // Where the problem stood, said again word for word, is no development.
2612
3457
  nothingNew: ruling => ruling.settledTensionId === null && ruling.newTension === null && ruling.effects.length === 0 && ruling.record.trim() === stalled.summary.trim(),
2613
3458
  });
@@ -2621,21 +3466,32 @@ async function stallCheck(session, due) {
2621
3466
  throw error;
2622
3467
  }
2623
3468
  }
3469
+ async function runDirectorCheck(session, due) {
3470
+ return runDirectorJob({
3471
+ get state() { return session.state; },
3472
+ complete: (call, actorId) => session.complete(call, actorId),
3473
+ commit: fields => session.commit(fields),
3474
+ takeTurn: key => session.takeTurn(key),
3475
+ canSpend: () => session.canSpend(),
3476
+ }, due);
3477
+ }
2624
3478
  // A world happening that fell due is carried out by the Game Master: the ambulances
2625
3479
  // arrive, the fire spreads or dies, the storm hits, security walks in.
2626
3480
  async function worldFollowUp(session, due) {
2627
3481
  if (due.series === 'stall-check')
2628
3482
  return stallCheck(session, due);
3483
+ if (due.series === 'director-check')
3484
+ return runDirectorCheck(session, due);
2629
3485
  const state = session.state;
2630
3486
  const placeId = due.placeId && state.places[due.placeId] ? due.placeId : session.player().placeId;
2631
3487
  const beat = due.beat;
2632
3488
  // A deadline whose problem was settled first does not happen; no one needs to rule it.
2633
3489
  const settledFirst = beat?.unless ? state.tensions.find(tension => tension.id === beat.unless.settled && tension.status === 'settled') : undefined;
2634
3490
  if (settledFirst) {
2635
- session.commit({ kind: 'world', actorId: null, placeId, summary: `Averted: ${due.intent} (${settledFirst.title} was settled first)`.slice(0, 2000), narration: null, outcome: null, minutes: 0,
3491
+ session.commit({ kind: 'world', actorId: null, placeId, summary: phrase('deadline.avertedWith', { intent: due.intent, title: settledFirst.title }).slice(0, 2000), narration: null, outcome: null, minutes: 0,
2636
3492
  effects: [{ kind: 'unschedule', scheduledId: due.id }, ...nextTime(due)(state),
2637
- ...(beat.deadline ? [{ kind: 'deadline.passed', what: due.intent.slice(0, MAX_LINE), outcome: `Averted: ${settledFirst.title} was settled first.`.slice(0, MAX_LINE),
2638
- ...(state.engine >= AVERTED_ENGINE ? { averted: true } : {}) }] : [])],
3493
+ ...(beat.deadline ? [{ kind: 'deadline.passed', what: due.intent.slice(0, MAX_LINE), outcome: phrase('deadline.averted', { title: settledFirst.title }).slice(0, MAX_LINE),
3494
+ ...(({ averted: true })) }] : [])],
2639
3495
  causeSeq: null, importance: 2, suggestions: [], ...quiet });
2640
3496
  return true;
2641
3497
  }
@@ -2643,10 +3499,13 @@ async function worldFollowUp(session, due) {
2643
3499
  const typed = (world) => beatResults(world, placeId, beat);
2644
3500
  try {
2645
3501
  const again = nextTime(due);
3502
+ const chain = ({ id: due.chain ?? due.id, link: due.link ?? 0 });
2646
3503
  await resolve(session, {
2647
3504
  phase: 'world', actorId: null, placeId, kind: 'world', causeSeq: due.sourceSeq || null, extraEffects: [{ kind: 'unschedule', scheduledId: due.id }], clears: again, concerns: due.targetId,
3505
+ ...(chain === undefined ? {} : { chain }),
2648
3506
  input: (errors, fitted, focusIds) => gameMasterWorldInput(session.state, { intent: due.intent, placeId, sourceSeq: due.sourceSeq, targetId: due.targetId, id: due.id,
2649
- ...(due.everyMinutes === undefined ? {} : { everyMinutes: due.everyMinutes }), alreadyTrue: typed(session.state).map(effect => describeResult(session.state, effect)) }, errors, fitted, focusIds),
3507
+ ...(due.everyMinutes === undefined ? {} : { everyMinutes: due.everyMinutes }), alreadyTrue: typed(session.state).map(effect => describeResult(session.state, effect)),
3508
+ ...(chain === undefined ? {} : { chain }) }, errors, fitted, focusIds),
2650
3509
  rulingEffects: (world, ruling) => [...typed(world),
2651
3510
  ...(beat?.deadline ? [{ kind: 'deadline.passed', what: due.intent.slice(0, MAX_LINE), outcome: (ruling.observed ?? ruling.record).slice(0, MAX_LINE) }] : [])],
2652
3511
  ...(beat?.reach ? { reach: { reach: beat.reach, notice: beat.heard ?? null } } : {}),
@@ -2656,7 +3515,7 @@ async function worldFollowUp(session, due) {
2656
3515
  // A happening that comes back is told anew each time.
2657
3516
  repeats: ruling => {
2658
3517
  const before = due.everyMinutes === undefined ? undefined : earlierTimes(session.state, due.sourceSeq).find(time => time.what === ruling.observed);
2659
- return before ? `This is word for word what happened at ${before.at}; tell what happens this time.` : null;
3518
+ return before ? phrase('happening.wordForWord', { at: before.at }) : null;
2660
3519
  },
2661
3520
  // People there perceive the happening, never the intent or record that caused it.
2662
3521
  trigger: ruling => ({ kind: 'world', actorId: null, text: ruling.observed ?? ruling.narration, narration: ruling.narration }),
@@ -2670,7 +3529,7 @@ async function worldFollowUp(session, due) {
2670
3529
  throw error;
2671
3530
  // A deadline comes whether or not anyone can tell it well: a little after its time it happens
2672
3531
  // with what its data says it changes, in its own words and as far as it carries.
2673
- if (beat?.deadline && session.state.clock - due.at >= DEADLINE_GRACE_MINUTES) {
3532
+ if (beat?.deadline && session.state.clock - due.at >= pace(session.state.calendar, 'deadlineGrace')) {
2674
3533
  const world = session.state;
2675
3534
  session.commit({ kind: 'world', actorId: null, placeId, summary: due.intent, narration: null, outcome: null, minutes: 0,
2676
3535
  effects: [{ kind: 'unschedule', scheduledId: due.id }, ...nextTime(due)(world), ...typed(world),
@@ -2688,7 +3547,7 @@ async function idleTick(session) {
2688
3547
  const state = session.state;
2689
3548
  const lastDecision = (personId) => [...state.events].reverse().find(event => event.actorId === personId && event.kind === 'plan')?.seq ?? 0;
2690
3549
  // A promise kept later is no plan for now; the person still decides what to do meanwhile.
2691
- const idle = Object.values(state.people).filter(person => !person.isPlayer && !person.incapacitated && person.plan === null
3550
+ const idle = Object.values(state.people).filter(person => !person.isPlayer && !person.incapacitated && !person.incidental && person.plan === null
2692
3551
  && !hasPlanned(state, person.id))
2693
3552
  .sort((left, right) => lastDecision(left.id) - lastDecision(right.id) || left.id.localeCompare(right.id));
2694
3553
  for (const person of idle.slice(0, MAX_DUE_ITEMS_PER_STEP)) {
@@ -2697,9 +3556,10 @@ async function idleTick(session) {
2697
3556
  await carryOutPlan(session, { id: generatedId(session.state.engine, 'idle', [session.state.revision + 1, person.id]), at: session.state.clock, personId: person.id, kind: 'plan', intent: 'idle', placeId: null, targetId: null, sourceSeq: session.state.revision, importance: 1 }, false);
2698
3557
  }
2699
3558
  }
2700
- function parsePlan(answer) {
3559
+ function parsePlan(answer, calendar) {
2701
3560
  const value = answer;
2702
- const actions = ['go', 'speak', 'message', 'attempt', 'go-home', 'wait'];
3561
+ const restAction = restActionOf(calendar);
3562
+ const actions = ['go', 'speak', 'message', 'attempt', 'wait', ...(restAction === null ? [] : [restAction])];
2703
3563
  if (!value || typeof value !== 'object' || typeof value.action !== 'string' || !actions.includes(value.action) || typeof value.mood !== 'string')
2704
3564
  throw new LivingWorldError('inference-invalid', 'The plan answer is malformed');
2705
3565
  const text = typeof value.text === 'string' && value.text.trim() !== '' ? value.text.trim().slice(0, MAX_SPOKEN) : null;
@@ -2710,13 +3570,70 @@ function parsePlan(answer) {
2710
3570
  targetId: typeof value.targetId === 'string' ? value.targetId : null,
2711
3571
  text,
2712
3572
  mood: cleanMood(value.mood, 'Present'),
2713
- nextPlan: parsePlanValue(value.nextPlan, 60),
3573
+ nextPlan: parsePlanValue(value.nextPlan, pace(calendar, 'idleWait')),
2714
3574
  request: request && typeof request.topic === 'string' && request.topic.trim() !== ''
2715
3575
  ? { topic: request.topic.trim().slice(0, 600), priorId: typeof request.priorId === 'string' ? request.priorId : null } : null,
3576
+ requestDecision: value.requestDecision && typeof value.requestDecision === 'object'
3577
+ && typeof value.requestDecision.id === 'string'
3578
+ && ['answered', 'accepted', 'refused', 'done'].includes(value.requestDecision.status)
3579
+ ? { id: value.requestDecision.id, status: value.requestDecision.status } : null,
3580
+ commitmentDecision: value.commitmentDecision && typeof value.commitmentDecision === 'object'
3581
+ && typeof value.commitmentDecision.id === 'string'
3582
+ && ['kept', 'broken'].includes(value.commitmentDecision.status)
3583
+ ? { id: value.commitmentDecision.id, status: value.commitmentDecision.status } : null,
2716
3584
  stance: ['undecided', 'cooperate', 'refuse', 'report', 'avoid', 'confront'].includes(value.stance) ? value.stance : null,
2717
- ballot: parseBallot(value.ballot),
3585
+ choose: value.choose && typeof value.choose === 'object' && typeof value.choose.entityId === 'string'
3586
+ && typeof value.choose.slotId === 'string' && typeof value.choose.option === 'string'
3587
+ ? { entityId: value.choose.entityId, slotId: value.choose.slotId, option: value.choose.option } : null,
2718
3588
  };
2719
3589
  }
3590
+ async function renewIncidental(session, due) {
3591
+ const state = session.state;
3592
+ const person = state.people[due.personId];
3593
+ const plan = { intent: person.plan?.intent ?? phrase('plan.carryOn'), ...(person.plan?.seen ? { seen: person.plan.seen } : {}),
3594
+ placeId: null, targetId: null, inMinutes: pace(state.calendar, 'defaultActivity') };
3595
+ session.commit({ kind: 'plan', actorId: null, placeId: person.placeId, summary: phrase('act.carriesOn', { name: person.name, intent: plan.intent }).slice(0, 2000), narration: null, outcome: null,
3596
+ minutes: 0, effects: planEffects(state, person.id, plan, state.revision + 1), causeSeq: due.sourceSeq || null, importance: 1, suggestions: [], ...quiet });
3597
+ return true;
3598
+ }
3599
+ // A routine plan comes due with nothing typed changed for its person: they continue the activity.
3600
+ function routinePlanUnchanged(state, due) {
3601
+ if ((state.clockRate === null) || due.selfPlanned !== true || due.importance > ROUTINE_PLAN_IMPORTANCE || isDecision(due) || due.personId === null)
3602
+ return false;
3603
+ const person = state.people[due.personId];
3604
+ if (!person || person.isPlayer || person.incapacitated || person.departed !== undefined || person.offstage !== undefined)
3605
+ return false;
3606
+ if (carriedOnTooLong(state, person))
3607
+ return false;
3608
+ // An open ask or promise is a deadline of theirs: it is a typed reason to decide again.
3609
+ if (person.commitments.some(commitment => commitment.status === 'open')
3610
+ || state.requests.some(request => request.status === 'open' && request.senderId === person.id))
3611
+ return false;
3612
+ if (person.planBasisSeq === undefined)
3613
+ return false;
3614
+ if (due.waitingForExchange === true && liveExchange(state, person.id) === null)
3615
+ return false;
3616
+ return person.situationSeq === undefined || person.situationSeq <= person.planBasisSeq;
3617
+ }
3618
+ // Carrying on keeps the activity, its place and its person; only its clock is set forward.
3619
+ async function carryOnPlan(session, due) {
3620
+ const state = session.state;
3621
+ const person = state.people[due.personId];
3622
+ const plan = { intent: person.plan?.intent ?? due.intent, ...(person.plan?.seen ? { seen: person.plan.seen } : {}),
3623
+ placeId: person.plan?.placeId ?? due.placeId, targetId: person.plan?.targetId ?? due.targetId,
3624
+ inMinutes: due.waitingForExchange === true ? pace(state.calendar, 'exchangeCheck') : pace(state.calendar, 'defaultActivity') };
3625
+ const effects = [
3626
+ ...state.schedule.filter(item => item.personId === person.id && item.kind === 'plan' && !isDecision(item)).map((item) => ({ kind: 'unschedule', scheduledId: item.id })),
3627
+ { kind: 'plan', personId: person.id, plan: { intent: plan.intent, ...(plan.seen ? { seen: plan.seen } : {}), placeId: plan.placeId, targetId: plan.targetId, dueAt: state.clock + plan.inMinutes },
3628
+ ...(person.planBasisSeq === undefined ? {} : { basisSeq: person.planBasisSeq }) },
3629
+ { kind: 'schedule', scheduledId: generatedId(state.engine, 'plan', [state.revision + 1, person.id], `plan-${state.revision + 1}-${person.id}`, true), personId: person.id,
3630
+ inMinutes: plan.inMinutes, intent: plan.intent, placeId: plan.placeId, targetId: plan.targetId, scheduleKind: 'plan', importance: ROUTINE_PLAN_IMPORTANCE, selfPlanned: true,
3631
+ ...(due.waitingForExchange === true ? { waitingForExchange: true } : {}) },
3632
+ ];
3633
+ session.commit({ kind: 'plan', actorId: person.id, placeId: person.placeId, summary: phrase('act.carriesOn', { name: person.name, intent: plan.intent }).slice(0, 2000), narration: null, outcome: null,
3634
+ minutes: 0, effects, causeSeq: due.sourceSeq || null, importance: 1, suggestions: [], ...quiet });
3635
+ return true;
3636
+ }
2720
3637
  async function carryOutPlan(session, due, scheduled) {
2721
3638
  const release = await session.takeTurn(due.personId);
2722
3639
  try {
@@ -2726,6 +3643,14 @@ async function carryOutPlan(session, due, scheduled) {
2726
3643
  release();
2727
3644
  }
2728
3645
  }
3646
+ export function duePlanCard(state, person, entry) {
3647
+ const where = entry.placeId !== null || entry.targetId !== null ? { placeId: entry.placeId, targetId: entry.targetId } : {};
3648
+ const late = state.clock - entry.at;
3649
+ const due = late >= pace(state.calendar, 'defaultActivity') ? { intent: entry.intent, ...where, overdueMinutes: late } : { intent: entry.intent, ...where };
3650
+ return person.plan !== null && person.plan.intent === due.intent
3651
+ ? { ...due, placeId: person.plan.placeId, targetId: person.plan.targetId }
3652
+ : due;
3653
+ }
2729
3654
  // The person's turn ends once their decision is recorded, before the world answers what they do.
2730
3655
  async function decidePlan(session, due, scheduled, release) {
2731
3656
  let asked = session.state;
@@ -2733,29 +3658,28 @@ async function decidePlan(session, due, scheduled, release) {
2733
3658
  // An idle person has no due plan; they decide from their own goals and state.
2734
3659
  // How late the plan is depends on the moment the person decides; a decision made again sees it anew.
2735
3660
  // A due item that names where and with whom, such as a promise to keep, says so.
2736
- const where = due.placeId !== null || due.targetId !== null ? { placeId: due.placeId, targetId: due.targetId } : {};
2737
- const dueAt = (world) => !scheduled ? null : world.clock - due.at >= 30 ? { intent: due.intent, ...where, overdueMinutes: world.clock - due.at } : { intent: due.intent, ...where };
3661
+ const dueAt = (world) => !scheduled ? null : duePlanCard(world, world.people[personId], due);
2738
3662
  let dueIntent = dueAt(asked);
2739
- // A member's turn to vote, given when voting opens.
2740
- const voteTurn = scheduled && due.id.startsWith('vote-');
3663
+ const choiceTurn = scheduled && isChoiceTurn(session.state, due);
2741
3664
  // The decision is made on the world as it is when the call goes.
2742
3665
  const build = (focusIds = []) => {
2743
3666
  asked = session.state;
2744
3667
  dueIntent = dueAt(asked);
2745
- const input = characterPlanInput(asked, asked.people[personId], dueIntent, voteTurn, focusIds);
2746
- return { input, responseSchema: scopedPlanResponseSchema(input) };
3668
+ const input = characterPlanInput(asked, asked.people[personId], dueIntent, choiceTurn, focusIds, due.decision);
3669
+ const responseSchema = scopedPlanResponseSchema(input, asked.engine, restActionOf(asked.calendar));
3670
+ return { input, responseSchema, system: systemFor('character-plan', responseSchema, input, planResponseSchema) };
2747
3671
  };
2748
3672
  // The world goes on while the person decides. A decision for an activity that another event has
2749
3673
  // already replaced, or by someone who can no longer act, is set aside, and a call still waiting its
2750
3674
  // turn for it is not sent; the newer course stands.
2751
3675
  const stillDue = (world) => {
2752
3676
  const who = world.people[personId];
2753
- return who !== undefined && !who.incapacitated && who.departed === undefined && who.away === undefined
3677
+ return who !== undefined && !who.incapacitated && who.departed === undefined && who.offstage === undefined
2754
3678
  && (scheduled ? world.schedule.some(item => item.id === due.id && item.sourceSeq === due.sourceSeq) : !hasPlanned(world, personId));
2755
3679
  };
2756
3680
  let answer;
2757
3681
  try {
2758
- answer = parsePlan(await session.complete({ role: 'character', phase: 'plan', system: CHARACTER_PLAN_SYSTEM, ...build(), ...LIVING_INFERENCE_LIMITS.plan }, personId, null, build, () => stillDue(session.state)));
3682
+ answer = parsePlan(await session.complete({ role: 'character', phase: 'plan', ...build(), ...LIVING_INFERENCE_LIMITS.plan }, personId, null, build, () => stillDue(session.state)), session.state.calendar);
2759
3683
  }
2760
3684
  catch (error) {
2761
3685
  // The plan stays pending when the model is unavailable; a malformed answer is a real failure.
@@ -2778,8 +3702,8 @@ async function decidePlan(session, due, scheduled, release) {
2778
3702
  decidedAt = now.revision;
2779
3703
  try {
2780
3704
  answer = parsePlan(await session.complete({
2781
- role: 'character', phase: 'plan', system: CHARACTER_PLAN_SYSTEM, ...build(), ...LIVING_INFERENCE_LIMITS.plan,
2782
- }, personId, null, build, () => stillDue(session.state)));
3705
+ role: 'character', phase: 'plan', ...build(), ...LIVING_INFERENCE_LIMITS.plan,
3706
+ }, personId, null, build, () => stillDue(session.state)), session.state.calendar);
2783
3707
  }
2784
3708
  catch (error) {
2785
3709
  if (!(error instanceof LivingWorldError) || (error.code !== 'inference-invalid' && error.code !== 'inference-unavailable'))
@@ -2804,32 +3728,72 @@ async function decidePlan(session, due, scheduled, release) {
2804
3728
  || answer.text !== null && saidAlready(state, personId, answer.text));
2805
3729
  if (unsaid)
2806
3730
  answer = { ...answer, action: 'wait', text: null };
2807
- // A vote cast in this decision is its own act, seen by those present, before whatever else the person does.
2808
- const voted = voteTurn ? ballotEffects(session.state, personId, answer.ballot, 'any') : [];
2809
- if (voted[0]?.kind === 'ballot') {
2810
- const voter = session.state.people[personId];
2811
- session.commit({ kind: 'reaction', actorId: personId, placeId: voter.placeId, summary: `${voter.name} votes ${voted[0].choice} on ${session.state.entities[voted[0].entityId].name}`.slice(0, 2000),
2812
- narration: null, outcome: null, minutes: 0, effects: voted, causeSeq: due.sourceSeq || null, importance: 3, suggestions: [], ...quiet });
3731
+ if (choiceTurn && answer.choose) {
3732
+ const chooser = session.state.people[personId];
3733
+ session.commit({ kind: 'reaction', actorId: personId, placeId: chooser.placeId, summary: phrase('choose.summary', { name: chooser.name, option: answer.choose.option, entity: session.state.entities[answer.choose.entityId]?.name ?? answer.choose.entityId }).slice(0, 2000),
3734
+ narration: null, outcome: null, minutes: 0, effects: [{ kind: 'cell.add', entityId: answer.choose.entityId, slotId: answer.choose.slotId, option: answer.choose.option, personId }],
3735
+ causeSeq: due.sourceSeq || null, importance: 3, suggestions: [], ...quiet });
2813
3736
  }
2814
3737
  state = session.state;
2815
3738
  const person = state.people[personId];
3739
+ const restAction = restActionOf(state.calendar);
2816
3740
  const seq = state.revision + 1;
2817
3741
  const live = session.live();
2818
3742
  // A plan that waits twice for itself ends here. In a live world a plan is an activity, and
2819
3743
  // a decision that names none keeps the person at what they were doing a while longer.
2820
- const again = !live && (state.engine >= BOUNDED_IDENTIFIERS_ENGINE ? due.replanned === true : due.id.endsWith('-again'));
3744
+ const again = !live && ((due.replanned === true));
2821
3745
  const stale = !live && answer.nextPlan !== null && answer.action === 'wait';
2822
3746
  if (stale && again)
2823
3747
  answer.nextPlan = null;
2824
3748
  // Someone another person there holds, by hand or by a typed gate, cannot walk away; a gate on speech,
2825
3749
  // messages or acts turns that plan into waiting.
2826
3750
  const kept = heldHere(state, person.id) || blockedByGate(state, person.id, 'move') !== null;
2827
- if (kept && (answer.action === 'go' || answer.action === 'go-home')) {
3751
+ if (kept && (answer.action === 'go' || answer.action === restAction)) {
2828
3752
  answer.action = 'wait';
2829
3753
  answer.text = null;
2830
3754
  }
3755
+ const decisionEffects = [];
3756
+ let decisionCounterpart = null;
3757
+ let decisionBroken = false;
3758
+ if (answer.commitmentDecision) {
3759
+ const commitment = person.commitments.find(candidate => candidate.id === answer.commitmentDecision.id);
3760
+ if (commitment && commitment.status === 'open') {
3761
+ decisionEffects.push({ kind: 'commitment.update', commitmentId: commitment.id, personId: person.id, status: answer.commitmentDecision.status });
3762
+ decisionCounterpart = commitment.toId;
3763
+ decisionBroken = answer.commitmentDecision.status === 'broken';
3764
+ if (answer.commitmentDecision.status === 'kept' && commitment.placeId !== undefined && commitment.placeId !== person.placeId && !kept) {
3765
+ answer.action = 'go';
3766
+ answer.placeId = commitment.placeId;
3767
+ }
3768
+ }
3769
+ }
3770
+ if (answer.requestDecision) {
3771
+ const request = state.requests.find(candidate => candidate.id === answer.requestDecision.id);
3772
+ if (request && request.status === 'open' && request.receiverId === person.id) {
3773
+ const status = answer.requestDecision.status === 'answered' ? 'accepted' : answer.requestDecision.status;
3774
+ decisionEffects.push({ kind: 'request.update', requestId: request.id, status, ...(answer.text === null ? {} : { answer: answer.text }) });
3775
+ decisionCounterpart = request.senderId;
3776
+ decisionBroken = status === 'refused';
3777
+ if (!isHere(state, request.senderId, person.placeId)) {
3778
+ const words = answer.text ?? (status === 'accepted' ? 'Yes.' : status === 'refused' ? 'No.' : 'Done.');
3779
+ decisionEffects.push(state.messageTravel ? dispatch(seq, 0, { fromId: person.id, toIds: [request.senderId], text: words, replies: false })
3780
+ : { kind: 'message', fromId: person.id, toIds: [request.senderId], text: words });
3781
+ }
3782
+ }
3783
+ }
3784
+ const reactToDecision = async (event) => {
3785
+ if (!event || !decisionBroken || decisionCounterpart === null || !isHere(session.state, decisionCounterpart, person.placeId))
3786
+ return;
3787
+ try {
3788
+ await react(session, [decisionCounterpart], event, { kind: 'decision', actorId: person.id, text: event.summary, narration: null }, 'reaction', true);
3789
+ }
3790
+ catch (error) {
3791
+ if (!(error instanceof LivingWorldError) || (error.code !== 'inference-unavailable' && error.code !== 'run-paused'))
3792
+ throw error;
3793
+ }
3794
+ };
2831
3795
  // Someone back from home stays at least two hours before going home again; they carry on with the day.
2832
- if (answer.action === 'go-home' && person.restedAt !== undefined && state.clock - person.restedAt < DAY_AWAY_MINUTES) {
3796
+ if (answer.action === restAction && person.restedAt !== undefined && state.clock - person.restedAt < offstageSpan(state.calendar)) {
2833
3797
  answer = { ...answer, action: 'wait', text: null, nextPlan: null };
2834
3798
  }
2835
3799
  const gatedPlan = answer.action === 'speak' ? 'speak' : answer.action === 'message' ? 'message' : answer.action === 'attempt' ? 'act' : null;
@@ -2837,11 +3801,42 @@ async function decidePlan(session, due, scheduled, release) {
2837
3801
  answer.action = 'wait';
2838
3802
  answer.text = null;
2839
3803
  }
2840
- const valid = answer.nextPlan && (answer.nextPlan.placeId === null || state.places[answer.nextPlan.placeId]) && (answer.nextPlan.targetId === null || state.people[answer.nextPlan.targetId]) ? answer.nextPlan : null;
3804
+ const target = answer.targetId && state.people[answer.targetId] ? state.people[answer.targetId] : null;
3805
+ // A live exchange with the player is closed in the scene before the person walks away from it.
3806
+ const exchange = (state.clockRate !== null) ? liveExchange(state, person.id) : null;
3807
+ const steppingOut = answer.action === 'wait' && answer.nextPlan !== null && answer.nextPlan.placeId !== null
3808
+ && answer.nextPlan.placeId !== person.placeId && state.places[answer.nextPlan.placeId] !== undefined
3809
+ && knowsPlace(state, person, answer.nextPlan.placeId);
3810
+ const leaving = answer.action === 'go' ? answer.placeId !== null && answer.placeId !== person.placeId
3811
+ : answer.action === restAction ? true
3812
+ : answer.action === 'speak' ? target !== null && target.placeId !== person.placeId
3813
+ : steppingOut;
3814
+ const closing = state.clockRate !== null && leaving && answer.text !== null && isHere(state, state.playerId, person.placeId)
3815
+ && (answer.action === 'go' || answer.action === restAction) && exchange?.awaitingAnswer !== true;
3816
+ let followImportance = ROUTINE_PLAN_IMPORTANCE;
3817
+ let answerFirst = [];
3818
+ let answerCause = null;
3819
+ let waitingExchange = false;
3820
+ if (exchange !== null && leaving && !closing) {
3821
+ // They stay, and decide again once the exchange has gone quiet; the leave is not forgotten.
3822
+ const wait = (Math.min(pace(state.calendar, 'exchangeCheck'), Math.max(pace(state.calendar, 'speech'), exchange.lastLineAt + pace(state.calendar, 'exchangeTurn') - state.clock)));
3823
+ answer = { ...answer, action: 'wait', placeId: null, text: null,
3824
+ nextPlan: { intent: phrase('act.stepOffstage', { name: state.people[state.playerId].name }), placeId: null, targetId: null,
3825
+ inMinutes: wait } };
3826
+ followImportance = (ROUTINE_PLAN_IMPORTANCE);
3827
+ waitingExchange = true;
3828
+ if ((exchange.awaitingAnswer)) {
3829
+ answerCause = exchange.lastLineSeq;
3830
+ answerFirst = [{ kind: 'schedule', scheduledId: generatedId(state.engine, 'answer', [seq, person.id]), personId: person.id, inMinutes: pace(state.calendar, 'speech'),
3831
+ intent: exchange.lastLineText, placeId: null, targetId: state.playerId, scheduleKind: 'answer', importance: 3 }];
3832
+ }
3833
+ }
3834
+ const valid = answer.nextPlan && (answer.nextPlan.placeId === null || (state.places[answer.nextPlan.placeId] !== undefined && knowsPlace(state, person, answer.nextPlan.placeId)))
3835
+ && (answer.nextPlan.targetId === null || state.people[answer.nextPlan.targetId]) ? answer.nextPlan : null;
2841
3836
  // Someone whose words were held back waits for an answer, not for their next try at saying them.
2842
- const named = valid && unsaid ? { ...valid, targetId: null, inMinutes: Math.max(valid.inMinutes, DEFAULT_ACTIVITY_MINUTES) } : valid;
2843
- const next = named ?? (live ? { intent: person.plan?.intent ?? 'Carry on with the day', ...(person.plan?.seen ? { seen: person.plan.seen } : {}),
2844
- placeId: null, targetId: null, inMinutes: DEFAULT_ACTIVITY_MINUTES } : null);
3837
+ const named = valid && unsaid ? { ...valid, targetId: null, inMinutes: Math.max(valid.inMinutes, pace(state.calendar, 'defaultActivity')) } : valid;
3838
+ const next = named ?? (live ? { intent: person.plan?.intent ?? phrase('plan.carryOn'), ...(person.plan?.seen ? { seen: person.plan.seen } : {}),
3839
+ placeId: null, targetId: null, inMinutes: pace(state.calendar, 'defaultActivity') } : null);
2845
3840
  const remaining = { ...state, schedule: state.schedule.filter(item => item.id !== due.id) };
2846
3841
  const mood = answer.mood;
2847
3842
  // A due decision about someone's serious act records where this person now stands.
@@ -2851,15 +3846,17 @@ async function decidePlan(session, due, scheduled, release) {
2851
3846
  ...(scheduled ? [{ kind: 'unschedule', scheduledId: due.id }] : []),
2852
3847
  ...(mood !== person.mood ? [{ kind: 'mood', personId: person.id, mood }] : []),
2853
3848
  ...(standing && answer.stance !== null ? [{ kind: 'stance', personId: person.id, actorId: standing.actorId, status: answer.stance, sourceSeq: standing.sourceSeq }] : []),
3849
+ ...decisionEffects,
2854
3850
  ];
2855
3851
  const newRequest = answer.request && answer.request.priorId === null && answer.targetId && answer.text
2856
3852
  && (answer.action === 'speak' || answer.action === 'message')
2857
3853
  ? [{ kind: 'request.open', requestId: generatedId(session.state.engine, 'request', [seq, person.id]), senderId: person.id,
2858
3854
  receiverId: answer.targetId, topic: answer.request.topic }]
2859
3855
  : reminding && !unsaid && prior ? [{ kind: 'request.remind', requestId: prior.id }] : [];
2860
- const follow = next ? planEffects(remaining, person.id, next, seq, stale ? '-again' : '') : [{ kind: 'plan', personId: person.id, plan: null }];
2861
- const cause = due.sourceSeq || null;
2862
- const target = answer.targetId && state.people[answer.targetId] ? state.people[answer.targetId] : null;
3856
+ const follow = next ? planEffects(remaining, person.id, next, seq, stale ? '-again' : '', followImportance, true, waitingExchange) : [{ kind: 'plan', personId: person.id, plan: null }];
3857
+ const cause = answerCause ?? (due.sourceSeq || null);
3858
+ // Words that close a live exchange are said here, before the walk, and the player perceives them.
3859
+ const closingEffects = closing && answer.action === 'go' && answer.text ? [{ kind: 'say', personId: person.id, text: answer.text, toIds: [state.playerId] }] : [];
2863
3860
  // A next activity somewhere else begins with the walk there, so nobody stands for hours getting ready to leave.
2864
3861
  if (!kept && answer.action === 'wait' && named?.placeId && named.placeId !== person.placeId && state.places[named.placeId]) {
2865
3862
  answer = { ...answer, action: 'go', placeId: named.placeId };
@@ -2868,7 +3865,8 @@ async function decidePlan(session, due, scheduled, release) {
2868
3865
  : answer.action === 'speak' && target !== null && target.placeId !== person.placeId);
2869
3866
  if (answer.action === 'attempt' && answer.text) {
2870
3867
  // A character's attempt goes through the same adjudication as the player's.
2871
- session.commit({ kind: 'plan', actorId: person.id, placeId: person.placeId, summary: `${person.name} decides: ${answer.text}`.slice(0, 2000), narration: null, outcome: null, minutes: 0, effects: [...base, ...follow], causeSeq: cause, importance: 2, suggestions: [], ...quiet });
3868
+ const event = session.commit({ kind: 'plan', actorId: person.id, placeId: person.placeId, summary: phrase('act.decides', { name: person.name, text: answer.text }).slice(0, 2000), narration: null, outcome: null, minutes: 0, effects: [...base, ...follow], causeSeq: cause, importance: 2, suggestions: [], ...quiet });
3869
+ await reactToDecision(event);
2872
3870
  release();
2873
3871
  try {
2874
3872
  await adjudicate(session, person.id, answer.text);
@@ -2880,48 +3878,55 @@ async function decidePlan(session, due, scheduled, release) {
2880
3878
  return true;
2881
3879
  }
2882
3880
  // Going home takes the person off the map, to rest, sleep or an errand, until their next activity ends.
2883
- if (answer.action === 'go-home') {
2884
- const reason = (answer.text ?? named?.intent ?? 'Away for a while').slice(0, MAX_LINE);
3881
+ if (answer.action === restAction) {
3882
+ const why = (answer.text ?? named?.intent ?? phrase('act.awayForAWhile')).slice(0, MAX_LINE);
2885
3883
  // A visitor brought in mid-story who goes home has left it; anyone else is home at least the night.
2886
3884
  if (person.newcomer) {
2887
- session.commit({ kind: 'move', actorId: person.id, placeId: person.placeId, summary: `${person.name} leaves: ${reason}`.slice(0, 2000), narration: null, outcome: null, minutes: 0,
2888
- effects: [...base, { kind: 'person.leave', personId: person.id, reason }], causeSeq: cause, importance: 2, suggestions: [], ...quiet, observed: `${person.name} leaves.` });
3885
+ const event = session.commit({ kind: 'move', actorId: person.id, placeId: person.placeId, summary: phrase('act.leaves', { name: `${person.name}${closingEffects.length > 0 ? phrase('act.saysAndFragment', { text: answer.text ?? '' }) : ''}`, why }).slice(0, 2000), narration: null, outcome: null, minutes: 0,
3886
+ effects: [...base, ...closingEffects, { kind: 'person.leave', personId: person.id, reason: why }], causeSeq: cause, importance: 2, suggestions: [], ...quiet,
3887
+ observed: phrase('act.leavesPlace', { name: `${person.name}${closingEffects.length > 0 ? phrase('act.saysAndFragment', { text: answer.text ?? '' }) : ''}`, place: state.places[person.placeId].name }) });
3888
+ await reactToDecision(event);
2889
3889
  return true;
2890
3890
  }
2891
3891
  // Home until the night is over, or until in time for a promise that falls due sooner.
2892
3892
  const promised = person.commitments.filter(commitment => commitment.status === 'open' && commitment.dueAt !== null && commitment.dueAt > state.clock)
2893
- .map(commitment => commitment.dueAt - state.clock - PROMISE_LEAD_MINUTES);
2894
- const night = isNight(state.clock) || state.clock - (person.restedAt ?? state.startClock ?? 0) >= LONG_DAY_MINUTES;
2895
- const least = night ? GO_HOME_MINUTES : DAY_AWAY_MINUTES;
2896
- const minutes = Math.max(AWAY_MINUTES.min, Math.min(Math.max(least, Math.min(AWAY_MINUTES.max, named?.inMinutes ?? least)), ...promised));
2897
- session.commit({ kind: 'move', actorId: person.id, placeId: person.placeId, summary: `${person.name} goes home: ${reason}`.slice(0, 2000), narration: null, outcome: null, minutes: 0,
2898
- effects: [...base, { kind: 'person.away', personId: person.id, minutes, reason }], causeSeq: cause, importance: 2, suggestions: [], ...quiet, observed: `${person.name} leaves.` });
3893
+ .map(commitment => commitment.dueAt - state.clock - pace(state.calendar, 'promiseLead'));
3894
+ const resting = restingAt(state.calendar, state.clock) || state.clock - (person.restedAt ?? state.startClock ?? 0) >= pace(state.calendar, 'longDay');
3895
+ const least = resting ? restSpan(state.calendar) : offstageSpan(state.calendar);
3896
+ const minutes = Math.max(pace(state.calendar, 'offstageMin'), Math.min(Math.max(least, Math.min(state.calendar.day, named?.inMinutes ?? least)), ...promised));
3897
+ const event = session.commit({ kind: 'move', actorId: person.id, placeId: person.placeId, summary: phrase('act.goesHome', { name: `${person.name}${closingEffects.length > 0 ? phrase('act.saysAndFragment', { text: answer.text ?? '' }) : ''}`, why }).slice(0, 2000), narration: null, outcome: null, minutes: 0,
3898
+ effects: [...base, ...closingEffects, { kind: 'person.offstage', personId: person.id, minutes, why }], causeSeq: cause, importance: 2, suggestions: [], ...quiet,
3899
+ observed: phrase('act.leavesPlace', { name: `${person.name}${closingEffects.length > 0 ? phrase('act.saysAndFragment', { text: answer.text ?? '' }) : ''}`, place: state.places[person.placeId].name }) });
3900
+ await reactToDecision(event);
2899
3901
  return true;
2900
3902
  }
2901
3903
  if (wantsToTravel) {
2902
3904
  const destination = answer.action === 'go' ? answer.placeId : target.placeId;
2903
3905
  const path = travelPath(state, person.placeId, destination);
2904
3906
  if (!path) {
2905
- session.commit({ kind: 'plan', actorId: person.id, placeId: person.placeId, summary: `${person.name} cannot reach ${state.places[destination].name}`, narration: null, outcome: null, minutes: 0, effects: [...base, ...follow], causeSeq: cause, importance: 1, suggestions: [], ...quiet });
3907
+ const event = session.commit({ kind: 'plan', actorId: person.id, placeId: person.placeId, summary: phrase('act.cannotReach', { name: person.name, place: state.places[destination].name }), narration: null, outcome: null, minutes: 0, effects: [...base, ...follow], causeSeq: cause, importance: 1, suggestions: [], ...quiet });
3908
+ await reactToDecision(event);
2906
3909
  return true;
2907
3910
  }
2908
3911
  // Words for someone elsewhere are chosen on arrival, from what is there then.
2909
3912
  const arrival = answer.action === 'speak' && answer.text
2910
- ? planEffects(remaining, person.id, { intent: `Say to ${target.name} what you came to say: ${answer.text}`.slice(0, 300), seen: `on the way to ${target.name}`,
2911
- placeId: destination, targetId: target.id, inMinutes: (path.length - 1) * TRAVEL_MINUTES_PER_HOP }, seq)
3913
+ ? planEffects(remaining, person.id, { intent: phrase('act.sayToIntent', { name: target.name, text: answer.text }).slice(0, 300), seen: phrase('act.onTheWay', { name: target.name }),
3914
+ placeId: destination, targetId: target.id, inMinutes: travelCost(state, path) }, seq, '', ROUTINE_PLAN_IMPORTANCE, false)
2912
3915
  : follow;
2913
- session.commit({
2914
- kind: 'move', actorId: person.id, placeId: person.placeId, summary: `${person.name} travels to ${state.places[destination].name}`, narration: null, outcome: null, minutes: (path.length - 1) * TRAVEL_MINUTES_PER_HOP,
2915
- observed: `${person.name} leaves toward ${firstRoom(state, path)}.`,
2916
- effects: [...base, { kind: 'move', personId: person.id, placeId: destination }, ...arrival], causeSeq: cause, importance: 2, suggestions: [], ...quiet,
3916
+ const event = session.commit({
3917
+ kind: 'move', actorId: person.id, placeId: person.placeId, summary: phrase('act.travels', { name: `${person.name}${closingEffects.length > 0 ? phrase('act.saysAndFragment', { text: answer.text ?? '' }) : ''}`, place: state.places[destination].name }), narration: null, outcome: null, minutes: travelCost(state, path),
3918
+ observed: phrase('act.leavesFor', { name: `${person.name}${closingEffects.length > 0 ? phrase('act.saysAndFragment', { text: answer.text ?? '' }) : ''}`, place: state.places[destination].name }),
3919
+ effects: [...base, ...closingEffects, { kind: 'move', personId: person.id, placeId: destination }, ...arrival], causeSeq: cause, importance: 2, suggestions: [], ...quiet,
2917
3920
  });
3921
+ await reactToDecision(event);
2918
3922
  return true;
2919
3923
  }
2920
3924
  if (answer.action === 'speak' && answer.text && target && isHere(state, target.id, person.placeId)) {
2921
3925
  const event = session.commit({
2922
- kind: 'reaction', actorId: person.id, placeId: person.placeId, summary: `${person.name} says to ${target.name}: "${answer.text}"`.slice(0, 2000), narration: null, outcome: null, minutes: SPEECH_MINUTES,
3926
+ kind: 'reaction', actorId: person.id, placeId: person.placeId, summary: phrase('act.saysTo', { name: person.name, target: target.name, text: answer.text }).slice(0, 2000), narration: null, outcome: null, minutes: pace(session.state.calendar, 'speech'),
2923
3927
  effects: [...base, { kind: 'say', personId: person.id, text: answer.text, toIds: [target.id] }, ...newRequest, ...follow], causeSeq: cause, importance: 3, suggestions: [], ...quiet,
2924
3928
  });
3929
+ await reactToDecision(event);
2925
3930
  release();
2926
3931
  await replyBetween(session, person.id, target.id, event, answer.text);
2927
3932
  return true;
@@ -2929,25 +3934,55 @@ async function decidePlan(session, due, scheduled, release) {
2929
3934
  if (answer.action === 'message' && answer.text && target) {
2930
3935
  const travel = state.messageTravel;
2931
3936
  const opened = newRequest[0]?.kind === 'request.open' ? { requestId: newRequest[0].requestId, topic: newRequest[0].topic } : undefined;
2932
- session.commit({
2933
- kind: 'message', actorId: person.id, placeId: person.placeId, summary: `${person.name} sends a message to ${target.name}${travel ? ` ${travel.how}` : ''}`, narration: null, outcome: null, minutes: MESSAGE_MINUTES,
3937
+ const event = session.commit({
3938
+ kind: 'message', actorId: person.id, placeId: person.placeId, summary: phrase('message.sends', { name: person.name, to: target.name, how: travel ? phrase('message.how', { how: travel.how }) : '' }), narration: null, outcome: null, minutes: pace(session.state.calendar, 'message'),
2934
3939
  effects: travel ? [...base, dispatch(seq, 0, { fromId: person.id, toIds: [target.id], text: answer.text, replies: true, request: opened }),
2935
3940
  ...newRequest.filter(effect => effect.kind === 'request.remind'), ...follow] : [
2936
3941
  ...base, { kind: 'message', fromId: person.id, toIds: [target.id], text: answer.text }, ...newRequest,
2937
- ...(target.isPlayer ? [] : [{ kind: 'schedule', scheduledId: generatedId(session.state.engine, 'reply', [seq, target.id]), personId: target.id, inMinutes: MESSAGE_REPLY_DELAY_MINUTES, intent: answer.text, placeId: null, targetId: person.id, scheduleKind: 'reply' }]),
3942
+ ...(target.isPlayer ? [] : [{ kind: 'schedule', scheduledId: generatedId(session.state.engine, 'reply', [seq, target.id]), personId: target.id, inMinutes: pace(session.state.calendar, 'messageReplyDelay'), intent: answer.text, placeId: null, targetId: person.id, scheduleKind: 'reply' }]),
2938
3943
  ...follow,
2939
3944
  ],
2940
3945
  causeSeq: cause, importance: 3, suggestions: [], ...quiet,
2941
3946
  });
3947
+ await reactToDecision(event);
2942
3948
  return true;
2943
3949
  }
2944
- session.commit({
3950
+ const event = session.commit({
2945
3951
  kind: 'plan', actorId: person.id, placeId: person.placeId, summary: next ? `${person.name} makes a plan: ${next.intent}`.slice(0, 2000) : dueIntent?.overdueMinutes === undefined ? `${person.name} waits` : `${person.name} drops the overdue plan and waits`, narration: null, outcome: null, minutes: 0,
2946
- effects: [...base, ...follow], causeSeq: cause, importance: 1, suggestions: [], ...quiet,
3952
+ effects: [...base, ...answerFirst, ...follow], causeSeq: cause, importance: 1, suggestions: [], ...quiet,
2947
3953
  // What onlookers see, as a label beside the name, not a sentence the free text must finish.
2948
3954
  ...(next?.seen ? { observed: `${person.name}: ${next.seen}`.slice(0, 600) } : {}),
2949
3955
  ...(unsaid ? { droppedEffects: 1 } : {}),
2950
3956
  });
3957
+ await reactToDecision(event);
3958
+ return true;
3959
+ }
3960
+ async function answerInPerson(session, due) {
3961
+ const state = session.state;
3962
+ const person = state.people[due.personId];
3963
+ const fromId = due.targetId ?? state.playerId;
3964
+ const carrier = state.events.find(event => event.seq === due.sourceSeq);
3965
+ const causeSeq = carrier?.causeSeq ?? due.sourceSeq;
3966
+ const cause = state.events.find(event => event.seq === causeSeq);
3967
+ const answered = state.events.some(event => event.causeSeq === causeSeq
3968
+ && event.effects.some(effect => effect.kind === 'say' && effect.personId === person.id && effect.toIds.includes(fromId)));
3969
+ if (answered || cause === undefined || !isHere(state, person.id, state.people[fromId]?.placeId ?? '') || !cause.witnessIds.includes(person.id)) {
3970
+ session.commit({ kind: 'plan', actorId: person.id, placeId: person.placeId, summary: `${person.name} lets the question pass`, narration: null, outcome: null, minutes: 0,
3971
+ effects: [{ kind: 'unschedule', scheduledId: due.id }], causeSeq, importance: 1, suggestions: [], ...quiet, perceivedBy: [] });
3972
+ return true;
3973
+ }
3974
+ try {
3975
+ await react(session, [person.id], cause, { kind: 'speech', actorId: fromId, text: due.intent, narration: null }, 'reply', false);
3976
+ }
3977
+ catch (error) {
3978
+ if (error instanceof LivingWorldError && (error.code === 'inference-unavailable' || error.code === 'run-paused'))
3979
+ return false;
3980
+ throw error;
3981
+ }
3982
+ if (session.state.schedule.some(item => item.id === due.id))
3983
+ session.commit({ kind: 'plan', actorId: person.id, placeId: person.placeId,
3984
+ summary: `${person.name} answers`, narration: null, outcome: null, minutes: 0, effects: [{ kind: 'unschedule', scheduledId: due.id }],
3985
+ causeSeq, importance: 1, suggestions: [], ...quiet, perceivedBy: [] });
2951
3986
  return true;
2952
3987
  }
2953
3988
  async function answerMessage(session, due) {
@@ -2960,6 +3995,18 @@ async function answerMessage(session, due) {
2960
3995
  }
2961
3996
  }
2962
3997
  async function replyToMessage(session, due) {
3998
+ const answeringPlayer = due.targetId === session.state.playerId;
3999
+ if (answeringPlayer)
4000
+ session.answering(due.personId, true);
4001
+ try {
4002
+ return await replyToMessageNow(session, due);
4003
+ }
4004
+ finally {
4005
+ if (answeringPlayer)
4006
+ session.answering(due.personId, false);
4007
+ }
4008
+ }
4009
+ async function replyToMessageNow(session, due) {
2963
4010
  let state = session.state;
2964
4011
  const person = state.people[due.personId];
2965
4012
  const fromId = due.targetId ?? state.playerId;
@@ -2973,9 +4020,13 @@ async function replyToMessage(session, due) {
2973
4020
  return true;
2974
4021
  }
2975
4022
  let value;
2976
- const build = (focusIds = []) => ({ input: characterMessageReplyInput(session.state, session.state.people[person.id], { fromId, text: due.intent }, focusIds), responseSchema: messageReplyResponseSchema });
4023
+ const build = (focusIds = []) => {
4024
+ const input = characterMessageReplyInput(session.state, session.state.people[person.id], { fromId, text: due.intent }, focusIds, due.decision);
4025
+ const responseSchema = scopedMessageReplyResponseSchema(input, session.state.engine);
4026
+ return { input, responseSchema, system: systemFor('character-reply', responseSchema, input, messageReplyResponseSchema) };
4027
+ };
2977
4028
  try {
2978
- value = await session.complete({ role: 'character', phase: 'message-reply', system: CHARACTER_MESSAGE_SYSTEM, ...build(), ...LIVING_INFERENCE_LIMITS['message-reply'] }, person.id, due.sourceSeq, build);
4029
+ value = await session.complete({ role: 'character', phase: 'message-reply', ...build(), ...LIVING_INFERENCE_LIMITS['message-reply'] }, person.id, due.sourceSeq, build);
2979
4030
  }
2980
4031
  catch (error) {
2981
4032
  if (error instanceof LivingWorldError && error.code === 'inference-unavailable')
@@ -2993,28 +4044,35 @@ async function replyToMessage(session, due) {
2993
4044
  const raw = typeof value.reply === 'string' && value.reply.trim() !== '' ? value.reply.trim().slice(0, MAX_SPOKEN) : null;
2994
4045
  const reply = raw;
2995
4046
  const belief = value.belief && typeof value.belief === 'object' ? value.belief : null;
2996
- const plan = parsePlanValue(value.plan, 30);
4047
+ const plan = parsePlanValue(value.plan, pace(state.calendar, 'defaultActivity'));
2997
4048
  const trust = clampInt(value.trust, -20, 20, 0);
2998
4049
  const warmth = clampInt(value.warmth, -20, 20, 0);
4050
+ const requestDecision = value.requestDecision && typeof value.requestDecision === 'object'
4051
+ && typeof value.requestDecision.id === 'string'
4052
+ && ['answered', 'accepted', 'refused', 'done'].includes(value.requestDecision.status)
4053
+ ? { id: value.requestDecision.id, status: value.requestDecision.status } : null;
2999
4054
  const seq = state.revision + 1;
3000
4055
  const mood = cleanMood(value.mood, writer.mood);
4056
+ const decided = requestDecision === null ? undefined : state.requests.find(item => item.id === requestDecision.id);
3001
4057
  const effects = [
3002
4058
  { kind: 'unschedule', scheduledId: due.id },
3003
4059
  ...(mood !== writer.mood ? [{ kind: 'mood', personId: person.id, mood }] : []),
3004
4060
  ...(reply && blockedByGate(state, person.id, 'message') === null ? [state.messageTravel ? dispatch(seq, 0, { fromId: person.id, toIds: [fromId], text: reply, replies: false })
3005
4061
  : { kind: 'message', fromId: person.id, toIds: [fromId], text: reply }] : []),
4062
+ ...(requestDecision && decided && decided.status === 'open' ? [{ kind: 'request.update', requestId: decided.id,
4063
+ status: requestDecision.status === 'answered' ? 'accepted' : requestDecision.status, ...(reply === null ? {} : { answer: reply }) }] : []),
3006
4064
  ...((trust !== 0 || warmth !== 0) && fromId !== person.id && state.people[fromId] ? [{ kind: 'relationship', personId: person.id, targetId: fromId, trust, warmth, note: '' }] : []),
3007
4065
  ...(belief && typeof belief.subject === 'string' && typeof belief.claim === 'string' && belief.subject.trim() !== '' && belief.claim.trim() !== '' ? [{ kind: 'belief', personId: person.id, subject: belief.subject.trim().slice(0, 120), claim: belief.claim.trim().slice(0, 300), sourcePersonId: state.people[fromId] ? fromId : null,
3008
4066
  evidence: { kind: 'told', eventSeq: due.sourceSeq, sourceId: fromId } }] : []),
3009
4067
  // Someone answering from home decides what to do next once back.
3010
- ...(plan && !writer.away && (plan.placeId === null || state.places[plan.placeId]) && (plan.targetId === null || state.people[plan.targetId]) ? planEffects({ ...state, schedule: state.schedule.filter(item => item.id !== due.id) }, person.id, plan, seq) : []),
4068
+ ...(plan && !writer.offstage && (plan.placeId === null || state.places[plan.placeId]) && (plan.targetId === null || state.people[plan.targetId]) ? planEffects({ ...state, schedule: state.schedule.filter(item => item.id !== due.id) }, person.id, plan, seq) : []),
3011
4069
  ];
3012
4070
  session.commit({
3013
4071
  kind: 'message', actorId: person.id, placeId: person.placeId,
3014
4072
  summary: reply ? `${person.name} replies to ${personLabel(state, fromId)}'s message` : `${person.name} reads ${personLabel(state, fromId)}'s message and does not reply`,
3015
4073
  narration: null, outcome: null, minutes: 0, effects, causeSeq: due.sourceSeq || null, importance: 3, suggestions: [], ...quiet,
3016
4074
  // No one where they left sees someone at home write.
3017
- ...(writer.away ? { perceivedBy: [] } : {}),
4075
+ ...(writer.offstage ? { perceivedBy: [] } : {}),
3018
4076
  });
3019
4077
  return true;
3020
4078
  }