@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
@@ -0,0 +1,80 @@
1
+ import { type LivingInferenceCall } from './inference.js';
2
+ import { type LivingEvent, type LivingStateRaw } from './types.js';
3
+ export declare const DIRECTOR_STALL_COMMANDS = 4;
4
+ export declare const DIRECTOR_REPEATED_ASKS = 3;
5
+ export declare const DIRECTOR_QUIET_COMMANDS = 2;
6
+ export declare const DIRECTOR_SERIOUS_IMPORTANCE = 7;
7
+ export declare const DIRECTOR_HIGH_IMPORTANCE = 6;
8
+ export declare const DIRECTOR_TURN = "director:check";
9
+ export declare const DIRECTOR_CHECK_INTENT: string;
10
+ export type DirectorTrigger = 'repeated' | 'stalled' | 'quiet' | 'unanswered' | 'ending';
11
+ export type DirectorSignals = {
12
+ commandsSinceChange: number;
13
+ repeatedAsks: number;
14
+ repeatedWith: string[];
15
+ quietMinutes: number;
16
+ seriousMinutes: number;
17
+ triggers: DirectorTrigger[];
18
+ };
19
+ export type DirectorDevelopment = {
20
+ development: 'happening' | 'initiative' | 'complication';
21
+ intent: string;
22
+ reason: string;
23
+ personId: string | null;
24
+ tensionId: string | null;
25
+ placeId: string | null;
26
+ inMinutes: number;
27
+ };
28
+ export type DirectorHost = {
29
+ readonly state: LivingStateRaw;
30
+ complete(call: LivingInferenceCall, actorId: string | null): Promise<unknown>;
31
+ commit(fields: Omit<LivingEvent, 'seq' | 'at' | 'witnessIds' | 'nearbyIds' | 'channel'> & {
32
+ channel?: string | null;
33
+ }): LivingEvent;
34
+ takeTurn(key: string): Promise<() => void>;
35
+ canSpend(): boolean;
36
+ };
37
+ export declare function directorSignals(state: LivingStateRaw): DirectorSignals;
38
+ export declare function directorInput(state: LivingStateRaw, signals: DirectorSignals, previousErrors?: readonly string[]): Record<string, unknown>;
39
+ export declare const directorResponseSchema: {
40
+ type: string;
41
+ additionalProperties: boolean;
42
+ required: string[];
43
+ properties: {
44
+ development: Record<string, unknown>;
45
+ intent: Record<string, unknown>;
46
+ personId: Record<string, unknown>;
47
+ tensionId: Record<string, unknown>;
48
+ placeId: Record<string, unknown>;
49
+ inMinutes: Record<string, unknown>;
50
+ reason: Record<string, unknown>;
51
+ };
52
+ };
53
+ export declare function directorResponseSchemaFor(state: LivingStateRaw, signals: DirectorSignals): Readonly<Record<string, unknown>>;
54
+ export declare function parseDirectorDevelopment(answer: unknown, state: LivingStateRaw, signals?: DirectorSignals): DirectorDevelopment;
55
+ export declare function directorScheduledItem(state: LivingStateRaw, development: DirectorDevelopment): {
56
+ scheduledId: string;
57
+ personId: string | null;
58
+ scheduleKind: "plan";
59
+ intent: string;
60
+ placeId: string;
61
+ targetId: string;
62
+ inMinutes: number;
63
+ importance: number;
64
+ series: string;
65
+ chain: undefined;
66
+ link: undefined;
67
+ } | {
68
+ scheduledId: string;
69
+ personId: null;
70
+ scheduleKind: "world";
71
+ intent: string;
72
+ placeId: string;
73
+ targetId: string | null;
74
+ inMinutes: number;
75
+ importance: number;
76
+ series: string;
77
+ chain: string;
78
+ link: number;
79
+ };
80
+ export declare function runDirectorJob(host: DirectorHost, due: LivingStateRaw['schedule'][number]): Promise<boolean>;
@@ -0,0 +1,363 @@
1
+ import { generatedId } from './identifiers.js';
2
+ import { LIVING_INFERENCE_LIMITS } from './inference.js';
3
+ import { lastingChangeToken } from './mechanics.js';
4
+ import { clockLabel, LivingWorldError } from './types.js';
5
+ import { pace } from './scale.js';
6
+ import { phrase } from './phrases.js';
7
+ import { systemFor } from './prompts.js';
8
+ export const DIRECTOR_STALL_COMMANDS = 4;
9
+ export const DIRECTOR_REPEATED_ASKS = 3;
10
+ export const DIRECTOR_QUIET_COMMANDS = 2;
11
+ export const DIRECTOR_SERIOUS_IMPORTANCE = 7;
12
+ export const DIRECTOR_HIGH_IMPORTANCE = 6;
13
+ export const DIRECTOR_TURN = 'director:check';
14
+ export const DIRECTOR_CHECK_INTENT = phrase('director.checkIntent');
15
+ const PLAYER_ACTS = new Set(['move', 'speech', 'attempt', 'message', 'wait', 'keep-playing']);
16
+ function askTarget(event) {
17
+ for (const effect of event.effects) {
18
+ if (effect.kind === 'say')
19
+ return effect.toIds.length === 0 ? `place:${event.placeId ?? ''}` : [...effect.toIds].sort().join(',');
20
+ if (effect.kind === 'message' || effect.kind === 'dispatch')
21
+ return [...effect.toIds].sort().join(',');
22
+ }
23
+ return null;
24
+ }
25
+ function answersPlayer(state, event, playerId, actSeq) {
26
+ if (event.actorId === playerId)
27
+ return false;
28
+ for (const effect of event.effects) {
29
+ if (effect.kind === 'stance') {
30
+ if (effect.actorId === playerId && effect.status !== 'undecided' && effect.sourceSeq >= actSeq)
31
+ return true;
32
+ if (effect.personId === playerId && effect.status !== 'undecided')
33
+ return true;
34
+ }
35
+ if (effect.kind === 'request.open' && (effect.senderId === playerId || effect.receiverId === playerId))
36
+ return true;
37
+ if (effect.kind === 'request.update') {
38
+ const request = state.requests.find(candidate => candidate.id === effect.requestId);
39
+ if (request !== undefined && (request.senderId === playerId || request.receiverId === playerId))
40
+ return true;
41
+ }
42
+ if (effect.kind === 'commitment' && (effect.personId === playerId || effect.toId === playerId))
43
+ return true;
44
+ if (effect.kind === 'shift' && (effect.fromId === playerId || effect.toId === playerId))
45
+ return true;
46
+ if (effect.kind === 'hold' && effect.personId === playerId)
47
+ return true;
48
+ if (effect.kind === 'tension.update') {
49
+ const tension = state.tensions.find(candidate => candidate.id === effect.tensionId);
50
+ if (tension !== undefined && tension.participantIds.includes(playerId))
51
+ return true;
52
+ }
53
+ }
54
+ return false;
55
+ }
56
+ export function directorSignals(state) {
57
+ const playerId = state.playerId;
58
+ const events = state.events;
59
+ const bySeq = new Map(events.map(event => [event.seq, event]));
60
+ const playerCaused = (event) => {
61
+ let cause = event.causeSeq;
62
+ for (let hop = 0; hop < 8 && cause !== null; hop += 1) {
63
+ const source = bySeq.get(cause);
64
+ if (source === undefined)
65
+ return event.actorId === playerId;
66
+ if (source.actorId === playerId)
67
+ return true;
68
+ cause = source.causeSeq;
69
+ }
70
+ return event.actorId === playerId;
71
+ };
72
+ const seen = new Set();
73
+ let lastChange = 0;
74
+ for (const event of events) {
75
+ let changed = false;
76
+ for (const effect of event.effects) {
77
+ if (effect.kind === 'schedule' && effect.series === 'director') {
78
+ changed = true;
79
+ continue;
80
+ }
81
+ if (!playerCaused(event))
82
+ continue;
83
+ const token = lastingChangeToken(effect);
84
+ if (token === null || seen.has(token))
85
+ continue;
86
+ seen.add(token);
87
+ changed = true;
88
+ }
89
+ if (changed)
90
+ lastChange = event.seq;
91
+ }
92
+ const since = events.filter(event => event.seq > lastChange);
93
+ const commands = since.filter(event => event.actorId === playerId && PLAYER_ACTS.has(event.kind));
94
+ const asks = new Map();
95
+ for (const event of commands) {
96
+ const target = askTarget(event);
97
+ if (target !== null)
98
+ asks.set(target, (asks.get(target) ?? 0) + 1);
99
+ }
100
+ let repeatedAsks = 0;
101
+ for (const count of asks.values())
102
+ repeatedAsks = Math.max(repeatedAsks, count);
103
+ const repeatedWith = new Set();
104
+ for (const event of commands) {
105
+ const target = askTarget(event);
106
+ if (target === null || (asks.get(target) ?? 0) < DIRECTOR_REPEATED_ASKS)
107
+ continue;
108
+ for (const effect of event.effects) {
109
+ if (effect.kind !== 'say' && effect.kind !== 'message' && effect.kind !== 'dispatch')
110
+ continue;
111
+ for (const id of effect.toIds)
112
+ if (state.people[id] !== undefined)
113
+ repeatedWith.add(id);
114
+ }
115
+ }
116
+ let perceivedAt = null;
117
+ for (let index = events.length - 1; index >= 0; index -= 1) {
118
+ const event = events[index];
119
+ const developed = event.effects.some(effect => effect.kind === 'schedule' && effect.series === 'director');
120
+ if (!developed && event.importance < DIRECTOR_HIGH_IMPORTANCE)
121
+ continue;
122
+ const seen = event.perceivedBy ?? event.witnessIds;
123
+ if (developed || seen.includes(playerId)) {
124
+ perceivedAt = event.at;
125
+ break;
126
+ }
127
+ }
128
+ const quietMinutes = Math.max(0, state.clock - (perceivedAt ?? state.startClock ?? state.clock));
129
+ let serious = null;
130
+ for (let index = events.length - 1; index >= 0; index -= 1) {
131
+ const event = events[index];
132
+ if (event.actorId === playerId && event.importance >= DIRECTOR_SERIOUS_IMPORTANCE
133
+ && (event.kind === 'attempt' || event.kind === 'speech') && event.outcome !== 'impossible') {
134
+ serious = event;
135
+ break;
136
+ }
137
+ }
138
+ const answered = serious !== null && events.some(event => event.seq > serious.seq && answersPlayer(state, event, playerId, serious.seq));
139
+ const seriousMinutes = serious === null ? 0 : Math.max(0, state.clock - serious.at);
140
+ const triggers = [];
141
+ if (repeatedAsks >= DIRECTOR_REPEATED_ASKS)
142
+ triggers.push('repeated');
143
+ if (commands.length >= DIRECTOR_STALL_COMMANDS)
144
+ triggers.push('stalled');
145
+ if (quietMinutes >= pace(state.calendar, 'directorQuiet') && commands.length >= DIRECTOR_QUIET_COMMANDS)
146
+ triggers.push('quiet');
147
+ if (serious !== null && !answered && seriousMinutes >= pace(state.calendar, 'directorSerious'))
148
+ triggers.push('unanswered');
149
+ if (state.stoppingPoint !== null && state.tensions.some(tension => tension.status === 'open'))
150
+ triggers.push('ending');
151
+ return { commandsSinceChange: commands.length, repeatedAsks, repeatedWith: [...repeatedWith].sort(), quietMinutes, seriousMinutes, triggers };
152
+ }
153
+ function label(state, id) {
154
+ return state.people[id]?.name ?? state.entities[id]?.name ?? state.objects[id]?.name ?? state.places[id]?.name
155
+ ?? state.tensions.find(tension => tension.id === id)?.title ?? id;
156
+ }
157
+ export function directorInput(state, signals, previousErrors = []) {
158
+ const player = state.people[state.playerId];
159
+ const placeName = (id) => id === null ? null : state.places[id]?.name ?? null;
160
+ const open = state.tensions.filter(tension => tension.status === 'open');
161
+ const cast = Object.values(state.people).filter(person => !person.isPlayer && person.departed === undefined);
162
+ const recent = state.events.filter(event => event.actorId === state.playerId).slice(-6);
163
+ const perceived = state.events.filter(event => {
164
+ const seen = event.perceivedBy ?? event.witnessIds;
165
+ return seen.includes(state.playerId);
166
+ }).slice(-6);
167
+ return {
168
+ phase: 'director',
169
+ clock: clockLabel(state.calendar, state.clock),
170
+ clockMinutes: state.clock,
171
+ setting: { world: state.setting, opening: state.opening },
172
+ trigger: signals.triggers[0] ?? null,
173
+ triggers: [...signals.triggers],
174
+ measured: { commandsSinceChange: signals.commandsSinceChange, repeatedAsks: signals.repeatedAsks, quietMinutes: signals.quietMinutes, seriousMinutes: signals.seriousMinutes },
175
+ askedRepeatedly: signals.repeatedWith.map(id => ({ id, name: label(state, id) })),
176
+ player: { id: player.id, name: player.name, placeId: player.placeId, place: placeName(player.placeId), mood: player.mood, doing: player.plan?.seen ?? null },
177
+ problems: open.slice(-6).map(tension => ({ id: tension.id, title: tension.title, summary: tension.summary.slice(0, 400), since: clockLabel(state.calendar, tension.changedAt),
178
+ participants: tension.participantIds.slice(0, 8).map(id => ({ id, name: label(state, id) })) })),
179
+ deadlines: state.schedule.filter(item => item.beat?.deadline === true).slice(-6).map(item => ({ at: clockLabel(state.calendar, item.at), what: item.intent.slice(0, 300) })),
180
+ passedDeadlines: (state.passedDeadlines ?? []).slice(-4).map(item => ({ at: clockLabel(state.calendar, item.at), what: item.what.slice(0, 300), outcome: item.outcome.slice(0, 300) })),
181
+ people: cast.slice(-10).map(person => ({ id: person.id, name: person.name, role: person.role, placeId: person.placeId, place: placeName(person.placeId),
182
+ stance: state.stances.find(stance => stance.personId === person.id && stance.actorId === state.playerId)?.status ?? null,
183
+ warmth: person.relationships[state.playerId]?.warmth ?? null })),
184
+ places: Object.values(state.places).slice(-12).map(place => ({ id: place.id, name: place.name })),
185
+ recentPlayer: recent.map(event => ({ at: clockLabel(state.calendar, event.at), kind: event.kind, what: event.summary.slice(0, 300), outcome: event.outcome })),
186
+ perceived: perceived.map(event => ({ at: clockLabel(state.calendar, event.at), what: event.summary.slice(0, 300), importance: event.importance })),
187
+ stoppingPoint: state.stoppingPoint === null ? null : { at: clockLabel(state.calendar, state.stoppingPoint.at), title: state.stoppingPoint.title, summary: state.stoppingPoint.summary.slice(0, 300) },
188
+ ...(previousErrors.length === 0 ? {} : { previousErrors: [...previousErrors] }),
189
+ };
190
+ }
191
+ const field = (schema, description) => ({ ...schema, description });
192
+ const words = (maxLength) => ({ type: 'string', minLength: 1, maxLength });
193
+ const maybeId = (description) => field({ anyOf: [{ type: 'string', minLength: 1, maxLength: 64 }, { type: 'null' }] }, description);
194
+ export const directorResponseSchema = {
195
+ type: 'object',
196
+ additionalProperties: false,
197
+ required: ['development', 'intent', 'personId', 'tensionId', 'placeId', 'inMinutes', 'reason'],
198
+ properties: {
199
+ development: field({ type: 'string', enum: ['happening', 'initiative', 'complication'] }, 'initiative: one person with a stake comes to the player with an offer, a demand or a consequence, and the player feels it; complication: the stakes of one open problem rise. Choose one of these two whenever someone with a stake can act. happening: the world itself acts, such as a knock, a closure or a demand arriving, only when no person with a stake can act.'),
200
+ intent: field(words(600), 'What happens, or what the person means to do, in the world\'s terms. It is a proposal: the Game Master rules a happening, and a person\'s own mind decides what they do.'),
201
+ personId: maybeId('For an initiative, the id of the person who acts; otherwise null.'),
202
+ tensionId: maybeId('For a complication, the id of the open problem whose stakes rise; otherwise null.'),
203
+ placeId: maybeId('Where it happens, from the places shown; null for where the player is.'),
204
+ inMinutes: field({ type: 'integer', minimum: 1 }, 'How soon it begins, in the world\'s own ticks.'),
205
+ reason: field(words(300), 'Why this development now, from the measured signals.'),
206
+ },
207
+ };
208
+ export function directorResponseSchemaFor(state, signals) {
209
+ const excluded = new Set(signals.triggers.includes('repeated') ? signals.repeatedWith : []);
210
+ const candidates = Object.values(state.people).filter(person => !person.isPlayer && person.departed === undefined && person.offstage === undefined
211
+ && !person.incapacitated && !excluded.has(person.id)).map(person => person.id).sort();
212
+ const personId = candidates.length > 0
213
+ ? field({ anyOf: [{ type: 'string', enum: candidates }, { type: 'null' }] }, 'For an initiative, the id of the person who acts; otherwise null. The people the player keeps asking are left out, so the development comes from someone else.')
214
+ : field({ type: 'null' }, 'No one else can act; propose a complication or a happening.');
215
+ return { ...directorResponseSchema, properties: { ...directorResponseSchema.properties, personId,
216
+ inMinutes: field({ type: 'integer', minimum: 1, maximum: pace(state.calendar, 'directorLead') }, directorResponseSchema.properties.inMinutes.description) } };
217
+ }
218
+ function stakeholder(state) {
219
+ for (const tension of state.tensions) {
220
+ if (tension.status !== 'open')
221
+ continue;
222
+ for (const id of tension.participantIds) {
223
+ const person = state.people[id];
224
+ if (person === undefined || person.isPlayer || person.incapacitated || person.departed !== undefined || person.offstage !== undefined)
225
+ continue;
226
+ return person;
227
+ }
228
+ }
229
+ return null;
230
+ }
231
+ function fail(message) {
232
+ throw new LivingWorldError('inference-invalid', message);
233
+ }
234
+ function checkDevelopment(state, answer, signals) {
235
+ const value = answer;
236
+ if (value === null || typeof value !== 'object')
237
+ fail('The Director answer is malformed');
238
+ const development = value.development;
239
+ if (development !== 'happening' && development !== 'initiative' && development !== 'complication')
240
+ fail('The Director must propose one development');
241
+ const intent = typeof value.intent === 'string' ? value.intent.trim() : '';
242
+ if (intent === '' || intent.length > 600)
243
+ fail('The development needs an intent of 1 to 600 characters');
244
+ const reason = typeof value.reason === 'string' ? value.reason.trim() : '';
245
+ if (reason === '' || reason.length > 300)
246
+ fail('The development needs a reason of 1 to 300 characters');
247
+ const inMinutes = typeof value.inMinutes === 'number' && Number.isInteger(value.inMinutes) ? value.inMinutes : 0;
248
+ if (inMinutes < 1 || inMinutes > pace(state.calendar, 'directorLead'))
249
+ fail(`The development begins in 1 to ${pace(state.calendar, 'directorLead')} ticks`);
250
+ const placeId = value.placeId === null ? null : typeof value.placeId === 'string' ? value.placeId : undefined;
251
+ if (placeId === undefined || (placeId !== null && state.places[placeId] === undefined))
252
+ fail('The development names a place that is not in this world');
253
+ const personId = value.personId === null ? null : typeof value.personId === 'string' ? value.personId : undefined;
254
+ if (personId === undefined)
255
+ fail('The development names a person by id or null');
256
+ const tensionId = value.tensionId === null ? null : typeof value.tensionId === 'string' ? value.tensionId : undefined;
257
+ if (tensionId === undefined)
258
+ fail('The development names a problem by id or null');
259
+ if (development === 'initiative') {
260
+ const person = personId === null ? undefined : state.people[personId];
261
+ if (person === undefined || person.isPlayer || person.incapacitated || person.departed !== undefined || person.offstage !== undefined)
262
+ fail('An initiative needs a person here who can act');
263
+ if (signals?.triggers.includes('repeated') && signals.repeatedWith.includes(person.id)) {
264
+ fail(`${person.name} is the one the player keeps asking; bring a stakeholder from elsewhere, raise an open problem, or let the world act.`);
265
+ }
266
+ if (tensionId !== null)
267
+ fail('An initiative concerns a person, not a problem');
268
+ }
269
+ if (development === 'complication') {
270
+ const tension = tensionId === null ? undefined : state.tensions.find(candidate => candidate.id === tensionId);
271
+ if (tension === undefined || tension.status !== 'open')
272
+ fail('A complication needs an open problem');
273
+ if (personId !== null)
274
+ fail('A complication is a world happening, not a person\'s plan');
275
+ }
276
+ if (development === 'happening') {
277
+ if (personId !== null || tensionId !== null)
278
+ fail('A happening concerns no person or problem');
279
+ const person = stakeholder(state);
280
+ if (person !== null)
281
+ fail(`A happening reaches no one the player can feel. ${person.name} has a stake in an open problem and can act, so make it an initiative or a complication.`);
282
+ }
283
+ return { development, intent, reason, personId, tensionId, placeId, inMinutes };
284
+ }
285
+ export function parseDirectorDevelopment(answer, state, signals) {
286
+ return checkDevelopment(state, answer, signals);
287
+ }
288
+ export function directorScheduledItem(state, development) {
289
+ const revision = state.revision + 1;
290
+ const placeId = development.placeId ?? state.people[state.playerId].placeId;
291
+ if (development.development === 'initiative') {
292
+ return { scheduledId: generatedId(state.engine, 'director-plan', [revision, development.personId]), personId: development.personId, scheduleKind: 'plan',
293
+ intent: phrase('director.initiativeIntent'), placeId, targetId: state.playerId, inMinutes: development.inMinutes, importance: 5, series: 'director', chain: undefined, link: undefined };
294
+ }
295
+ const scheduledId = generatedId(state.engine, 'director-world', [revision, development.development]);
296
+ return { scheduledId, personId: null, scheduleKind: 'world', intent: development.intent, placeId, targetId: development.tensionId,
297
+ inMinutes: development.inMinutes, importance: 6, series: 'director', chain: scheduledId, link: 0 };
298
+ }
299
+ function nextCheck(state, minutes) {
300
+ const at = state.clock + minutes;
301
+ return { kind: 'schedule', scheduledId: generatedId(state.engine, 'director-check', [state.revision + 1, at]), personId: null, inMinutes: minutes,
302
+ intent: DIRECTOR_CHECK_INTENT, placeId: state.people[state.playerId].placeId, targetId: null, scheduleKind: 'world', importance: 1, series: 'director-check' };
303
+ }
304
+ function directorEvent(state, summary) {
305
+ return { kind: 'world', actorId: null, placeId: state.people[state.playerId].placeId, summary, narration: null, outcome: null, minutes: 0,
306
+ causeSeq: null, importance: 1, suggestions: [], reach: 'here', notice: null, perceivedBy: [] };
307
+ }
308
+ export async function runDirectorJob(host, due) {
309
+ const release = await host.takeTurn(DIRECTOR_TURN);
310
+ try {
311
+ const state = host.state;
312
+ if (state.paused || state.status === 'finished')
313
+ return false;
314
+ if (!state.schedule.some(item => item.id === due.id && item.sourceSeq === due.sourceSeq))
315
+ return true;
316
+ const signals = directorSignals(state);
317
+ if (signals.triggers.length === 0 || state.playerActedAt === undefined) {
318
+ return true;
319
+ }
320
+ let development = null;
321
+ let errors = [];
322
+ for (let attempt = 0; attempt < 2 && development === null; attempt += 1) {
323
+ if (!host.canSpend())
324
+ return false;
325
+ let answer;
326
+ try {
327
+ const input = directorInput(host.state, signals, errors);
328
+ answer = await host.complete({ role: 'director', phase: 'director', system: systemFor('director', directorResponseSchema, input),
329
+ input, responseSchema: directorResponseSchemaFor(host.state, signals), ...LIVING_INFERENCE_LIMITS.director }, null);
330
+ }
331
+ catch (error) {
332
+ if (error instanceof LivingWorldError && (error.code === 'inference-unavailable' || error.code === 'inference-invalid'))
333
+ return false;
334
+ throw error;
335
+ }
336
+ try {
337
+ development = checkDevelopment(host.state, answer, signals);
338
+ }
339
+ catch (error) {
340
+ if (!(error instanceof LivingWorldError) || error.code !== 'inference-invalid')
341
+ throw error;
342
+ errors = [error.message];
343
+ }
344
+ }
345
+ const now = host.state;
346
+ if (development === null) {
347
+ host.commit({ ...directorEvent(now, phrase('director.foundNothing')), effects: [{ kind: 'unschedule', scheduledId: due.id }, nextCheck(now, pace(now.calendar, 'directorCheck'))] });
348
+ return true;
349
+ }
350
+ const item = directorScheduledItem(now, development);
351
+ const chain = item.chain === undefined ? {} : { chain: item.chain, link: item.link };
352
+ const summary = development.development === 'initiative' ? phrase('director.initiativeSetInMotion') : phrase('director.setInMotion', { intent: development.intent });
353
+ host.commit({ ...directorEvent(now, summary.slice(0, 2000)),
354
+ effects: [{ kind: 'unschedule', scheduledId: due.id },
355
+ { kind: 'schedule', scheduledId: item.scheduledId, personId: item.personId, inMinutes: item.inMinutes, intent: item.intent, placeId: item.placeId, targetId: item.targetId,
356
+ scheduleKind: item.scheduleKind, importance: item.importance, series: item.series, ...chain },
357
+ nextCheck(now, pace(now.calendar, 'directorGap'))] });
358
+ return true;
359
+ }
360
+ finally {
361
+ release();
362
+ }
363
+ }