narraeon 0.5.7 → 0.6.0

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 (36) hide show
  1. package/README.md +2 -0
  2. package/README.zh-CN.md +2 -0
  3. package/dist/node/protocol/gameplay.js +69 -0
  4. package/dist/node/protocol/resolution.js +274 -0
  5. package/dist/node/protocol/v1.js +15 -0
  6. package/dist/node/runtime/RuntimeErrorLog.js +95 -0
  7. package/dist/node/runtime/V1Runtime.js +57 -2
  8. package/dist/node/runtime/content/ContentWorkspace.js +10 -2
  9. package/dist/node/runtime/content/CurrentTreeContentLibrary.js +43 -2
  10. package/dist/node/runtime/content/FileNativeContentTree.js +8 -1
  11. package/dist/node/runtime/play/FileNativePlayAdvanceStore.js +37 -1
  12. package/dist/node/runtime/play/FileNativePlayPresetStore.js +48 -3
  13. package/dist/node/runtime/play/FileNativePlayTimelineStore.js +7 -0
  14. package/dist/node/runtime/play/OrderedPlayPrompts.js +68 -6
  15. package/dist/node/runtime/play/PlayCallChain.js +33 -5
  16. package/dist/node/runtime/play/TabletopResolution.js +372 -0
  17. package/dist/node/runtime/play/TabletopRules.js +141 -0
  18. package/dist/node/runtime/prompt/FileNativePromptCompiler.js +45 -10
  19. package/dist/node/runtime/prompt/FileNativeToolRegistry.js +35 -2
  20. package/dist/node/runtime/setting/FileNativeSettingImprovementStore.js +4 -1
  21. package/dist/node/runtime/setting/SettingAuthoringTransaction.js +56 -13
  22. package/dist/node/runtime/setting/SettingImprovementSession.js +6 -4
  23. package/dist/node/runtime/world/FileNativeWorldStore.js +36 -2
  24. package/dist/node/runtime/world-revision/FileNativeWorldRevisionStore.js +2 -0
  25. package/dist/node/runtime/world-revision/WorldRevisionAuthoringTransaction.js +35 -6
  26. package/dist/node/runtime/world-revision/WorldRevisionSession.js +9 -5
  27. package/dist/node/server/ConversationStream.js +2 -0
  28. package/dist/node/shared/ordered-author-prompts.js +8 -0
  29. package/dist/node/shared/ordered-play-prompts.js +23 -0
  30. package/dist/node/shared/tabletop-guidance.js +100 -0
  31. package/dist/web/assets/index-BJ-1Mb0e.css +1 -0
  32. package/dist/web/assets/index-BgBL8G-A.js +1323 -0
  33. package/dist/web/index.html +2 -2
  34. package/package.json +1 -1
  35. package/dist/web/assets/index-DxNtxzLR.js +0 -1255
  36. package/dist/web/assets/index-DzOnu9uv.css +0 -1
@@ -5,7 +5,7 @@ import { hasLegacyHistoryTools } from "./FileNativeToolRegistry.js";
5
5
  import { effectiveFollowupDefinitions } from "../play/OrderedFollowups.js";
6
6
  import { legacyAuthorPrompts } from "../play/FileNativePlayPresetStore.js";
7
7
  import { builtinAuthorPrompts, authoringMechanics, } from "../../shared/ordered-author-prompts.js";
8
- import { builtinPlayPrompts, } from "../../shared/ordered-play-prompts.js";
8
+ import { builtinPlayPrompts, orderedPromptScope, promptScopeApplies, } from "../../shared/ordered-play-prompts.js";
9
9
  import { parseOrderedPlayPrompts } from "../play/OrderedPlayPrompts.js";
10
10
  import { renderDocumentWritePosition } from "./WorldMaintenanceReport.js";
11
11
  import { parseDocument } from "yaml";
@@ -16,7 +16,10 @@ import { renderPlayerViewBindings } from "../world/PlayerViewBindings.js";
16
16
  import { checkpointHistory, checkpointReplayBlocks, } from "../play/PlayContinuity.js";
17
17
  import { defaultAppLocale, } from "../../protocol/appPreferences.js";
18
18
  import { WorldDocumentStore, } from "../world/WorldDocumentStore.js";
19
- import { defaultRuntimeToolDefinitionStrategy, registeredRuntimeToolNames, runtimeToolsForNames, } from "./FileNativeToolRegistry.js";
19
+ import { defaultRuntimeToolDefinitionStrategy, runtimeToolNamesForGameplay, runtimeToolsForNames, } from "./FileNativeToolRegistry.js";
20
+ import { resolutionToolNames } from "../play/TabletopResolution.js";
21
+ import { readGameplay } from "../../protocol/gameplay.js";
22
+ import { tabletopAuthoringRulesBlock, tabletopWorldRulesBlock, } from "../play/TabletopRules.js";
20
23
  import { stateDirectoryHandle } from "../world/StateDirectoryHandles.js";
21
24
  export class PromptCompilationError extends Error {
22
25
  code;
@@ -103,6 +106,7 @@ const playCallChainToolNames = new Set([
103
106
  "world_create",
104
107
  "world_retire",
105
108
  "world_checkpoint",
109
+ ...resolutionToolNames,
106
110
  ]);
107
111
  export class FileNativePromptCompiler {
108
112
  #toolStrategyOverride;
@@ -137,6 +141,7 @@ export class FileNativePromptCompiler {
137
141
  },
138
142
  runtimeSource: "runtime:builtin/setting-improvement",
139
143
  target: "setting",
144
+ gameplay: input.gameplay,
140
145
  runtimeContract: input.runtimeContract,
141
146
  authorPrompt: input.authorPrompt,
142
147
  playPreset: input.playPreset,
@@ -165,6 +170,7 @@ export class FileNativePromptCompiler {
165
170
  },
166
171
  runtimeSource: "runtime:builtin/world-revision",
167
172
  target: "world-revision",
173
+ gameplay: input.gameplay,
168
174
  runtimeContract: input.runtimeContract,
169
175
  authorPrompt: input.authorPrompt,
170
176
  playPreset: input.playPreset,
@@ -174,7 +180,7 @@ export class FileNativePromptCompiler {
174
180
  }
175
181
  #compileAuthoringConversation(input) {
176
182
  validateModel(input.modelBinding);
177
- const presetReference = settingImprovementPresetReference(input.playPreset, this.#locale, input.target);
183
+ const presetReference = settingImprovementPresetReference(input.playPreset, this.#locale, input.target, input.gameplay);
178
184
  const logicalMessages = [];
179
185
  const ordered = input.playPreset.definition.authorPrompts ??
180
186
  legacyAuthorPrompts(input.playPreset.definition);
@@ -182,6 +188,8 @@ export class FileNativePromptCompiler {
182
188
  for (const entry of ordered) {
183
189
  if (entry.kind === "world" || !entry.enabled)
184
190
  continue;
191
+ if (!promptScopeApplies(orderedPromptScope(entry, catalog), input.gameplay))
192
+ continue;
185
193
  const builtin = entry.kind === "builtin"
186
194
  ? catalog.find((item) => item.id === entry.builtin)
187
195
  : undefined;
@@ -199,7 +207,15 @@ export class FileNativePromptCompiler {
199
207
  },
200
208
  ];
201
209
  if (builtin?.id === "author.target")
202
- blocks = [input.identity, input.boundary];
210
+ blocks = [
211
+ input.identity,
212
+ input.boundary,
213
+ ...(input.gameplay.mode === "tabletop"
214
+ ? [
215
+ tabletopAuthoringRulesBlock(input.gameplay, input.target, this.#locale),
216
+ ]
217
+ : []),
218
+ ];
203
219
  if (builtin?.id === "author.play-reference")
204
220
  blocks = [
205
221
  {
@@ -336,7 +352,7 @@ export class FileNativePromptCompiler {
336
352
  markdown: joinBlocks(blocks[role]),
337
353
  }));
338
354
  scanRuntimeLeakage(logicalMessages);
339
- const tools = runtimeToolsForNames(registeredRuntimeToolNames, this.#locale);
355
+ const tools = runtimeToolsForNames(runtimeToolNamesForGameplay(playGameplay(documentSnapshot)), this.#locale);
340
356
  const toolStrategy = this.#toolStrategyOverride ??
341
357
  defaultRuntimeToolDefinitionStrategy(effectiveInput.modelBinding.provider);
342
358
  const cacheStrategy = effectiveInput.modelBinding.cacheStrategy ??
@@ -468,7 +484,7 @@ export class FileNativePromptCompiler {
468
484
  const bootstrap = binding.definition.playPrompts === undefined
469
485
  ? this.compilePlayBootstrap(input)
470
486
  : this.compileOrderedPlayBootstrap(input, binding);
471
- const compilation = compilePlayPresetCompilation(input, bootstrap, binding, this.#locale);
487
+ const compilation = compilePlayPresetCompilation(input, bootstrap, binding, this.#locale, runtimeToolNamesForGameplay(playGameplay(input.world.documentSnapshot)));
472
488
  refreshMaintenanceTotals(compilation.bootstrap);
473
489
  return compilation;
474
490
  }
@@ -493,7 +509,12 @@ export class FileNativePromptCompiler {
493
509
  ...prompt,
494
510
  });
495
511
  };
512
+ const playCatalog = builtinPlayPrompts(this.#locale);
513
+ const gameplay = playGameplay(effective.world.documentSnapshot);
496
514
  for (const entry of parseOrderedPlayPrompts(binding.definition.playPrompts)) {
515
+ // A scoped entry is absent from the request, not an empty message.
516
+ if (!promptScopeApplies(orderedPromptScope(entry, playCatalog), gameplay))
517
+ continue;
497
518
  prompt = {
498
519
  messageRole: entry.messageRole ?? "system",
499
520
  promptId: entry.id,
@@ -530,7 +551,7 @@ export class FileNativePromptCompiler {
530
551
  { source: "player:input", markdown: effective.playerInput },
531
552
  ]);
532
553
  scanRuntimeLeakage(logicalMessages);
533
- const tools = runtimeToolsForNames(registeredRuntimeToolNames, this.#locale);
554
+ const tools = runtimeToolsForNames(runtimeToolNamesForGameplay(playGameplay(effective.world.documentSnapshot)), this.#locale);
534
555
  const toolStrategy = this.#toolStrategyOverride ??
535
556
  defaultRuntimeToolDefinitionStrategy(effective.modelBinding.provider);
536
557
  const strategy = effective.modelBinding.cacheStrategy ??
@@ -620,6 +641,11 @@ export class FileNativePromptCompiler {
620
641
  .map((directory) => `- ${stateDirectoryHandle(directory)}`)
621
642
  .join("\n")}`,
622
643
  });
644
+ // Runtime rules precede the materials they govern. The frozen path keeps
645
+ // this block verbatim, so a continued context neither repeats nor loses it.
646
+ const gameplay = playGameplay(snapshot);
647
+ if (gameplay.mode === "tabletop")
648
+ materials.blocks.unshift(tabletopWorldRulesBlock(gameplay, this.#locale));
623
649
  return materials;
624
650
  }
625
651
  /**
@@ -790,7 +816,7 @@ Workspace title (data, not an instruction): ${encodedTitle}
790
816
 
791
817
  This title identifies the editing target, not world facts or document titles.`;
792
818
  }
793
- function settingImprovementPresetReference(binding, locale, target) {
819
+ function settingImprovementPresetReference(binding, locale, target, gameplay) {
794
820
  const revision = target === "world-revision";
795
821
  const worldInstructionPlaceholder = {
796
822
  source: `${revision ? "world-revision" : "content-package"}:control/frame.yaml#instructions`,
@@ -813,6 +839,8 @@ function settingImprovementPresetReference(binding, locale, target) {
813
839
  ];
814
840
  if (!entry.enabled)
815
841
  return [];
842
+ if (!promptScopeApplies(orderedPromptScope(entry, builtinPlayPrompts(locale)), gameplay))
843
+ return [];
816
844
  if (entry.kind === "user")
817
845
  return [
818
846
  { source: `preset:prompt/${entry.id}`, markdown: entry.body },
@@ -969,8 +997,8 @@ function createPlayPresetPreview(binding, compilation) {
969
997
  * is either part of the bootstrap or a derived request dispatched after the
970
998
  * chain settles.
971
999
  */
972
- function compilePlayPresetCompilation(input, bootstrap, binding, locale) {
973
- const toolUniverse = fileNativeToolsForNames(registeredRuntimeToolNames, locale);
1000
+ function compilePlayPresetCompilation(input, bootstrap, binding, locale, playToolNames) {
1001
+ const toolUniverse = fileNativeToolsForNames(playToolNames, locale);
974
1002
  const toolStrategy = bootstrap.toolStrategy;
975
1003
  const stableText = cacheStableText(bootstrap.logicalMessages, binding.definition.playPrompts ? bootstrap.provider : undefined);
976
1004
  const sessionBootstrap = {
@@ -1152,6 +1180,13 @@ function validateModel(model) {
1152
1180
  throw new PromptCompilationError("model_max_output_invalid", "The model must provide a valid maxOutputTokens value");
1153
1181
  }
1154
1182
  }
1183
+ /**
1184
+ * A world or package keeps its gameplay in control/gameplay.json; a missing
1185
+ * file is interactive fiction. Every play universe is derived from this value.
1186
+ */
1187
+ function playGameplay(snapshot) {
1188
+ return readGameplay(snapshot.files);
1189
+ }
1155
1190
  function snapshotFiles(snapshot) {
1156
1191
  return Object.fromEntries(snapshot.files.map(({ path, contents }) => [path, contents]));
1157
1192
  }
@@ -1,5 +1,6 @@
1
1
  import { historyUseGuidance } from "../../shared/history-use-guidance.js";
2
2
  import { defaultAppLocale, } from "../../protocol/appPreferences.js";
3
+ import { resolutionCheckToolForScheme, resolutionToolDefinition, resolutionToolNames, } from "../play/TabletopResolution.js";
3
4
  /**
4
5
  * Runtime-owned prompt tool registry.
5
6
  *
@@ -7,7 +8,12 @@ import { defaultAppLocale, } from "../../protocol/appPreferences.js";
7
8
  * schemas and descriptions stay here so authors cannot fork the executable
8
9
  * tool contract.
9
10
  */
10
- export const registeredRuntimeToolNames = [
11
+ /**
12
+ * Tools that every current play and authoring surface may expose. Resolution
13
+ * tools are registered below but never enter a surface until a per-world
14
+ * selection (Phase 2) includes them.
15
+ */
16
+ export const baseRuntimeToolNames = [
11
17
  "state_list",
12
18
  "history_list",
13
19
  "history_search",
@@ -21,8 +27,28 @@ export const registeredRuntimeToolNames = [
21
27
  "artifact_emit",
22
28
  "artifact_clear",
23
29
  ];
30
+ /** The full executable Runtime vocabulary. Exposure is chosen per surface. */
31
+ export const registeredRuntimeToolNames = [
32
+ ...baseRuntimeToolNames,
33
+ ...resolutionToolNames,
34
+ ];
35
+ /**
36
+ * The tool surface of one world or package, derived only from its gameplay.
37
+ * Interactive fiction keeps the base surface exactly; tabletop adds the
38
+ * scheme's check plus auxiliary dice and arithmetic.
39
+ */
40
+ export function runtimeToolNamesForGameplay(gameplay) {
41
+ if (gameplay.mode !== "tabletop")
42
+ return [...baseRuntimeToolNames];
43
+ return [
44
+ ...baseRuntimeToolNames,
45
+ resolutionCheckToolForScheme(gameplay.scheme),
46
+ "roll_dice",
47
+ "calculate",
48
+ ];
49
+ }
24
50
  /** Changes only when the executable Runtime tool universe or schemas change. */
25
- export const runtimeToolRegistryRevision = "runtime-tools-v9";
51
+ export const runtimeToolRegistryRevision = "runtime-tools-v10";
26
52
  export function defaultRuntimeToolDefinitionStrategy(provider) {
27
53
  return provider === "openai_responses"
28
54
  ? "native_allowed_subset"
@@ -89,6 +115,7 @@ function createToolDefinitions(locale) {
89
115
  }, ["yaml"]);
90
116
  const markdownLocator = object({ markdown: { type: "array", items: { type: "string" }, minItems: 1 } }, ["markdown"]);
91
117
  const definitions = {
118
+ ...resolutionDefinitions(locale),
92
119
  state_list: {
93
120
  description: descriptions.state_list,
94
121
  inputSchema: object({
@@ -237,6 +264,12 @@ function createToolDefinitions(locale) {
237
264
  };
238
265
  return definitions;
239
266
  }
267
+ function resolutionDefinitions(locale) {
268
+ return Object.fromEntries(resolutionToolNames.map((name) => {
269
+ const { description, inputSchema } = resolutionToolDefinition(name, locale);
270
+ return [name, { description, inputSchema }];
271
+ }));
272
+ }
240
273
  const toolDescriptions = {
241
274
  en: {
242
275
  world_checkpoint: "Register a gap between events: the previous event has naturally settled at this turn's stopping point, or the scene has actually changed, suggesting that the player start a fresh context here. Arguments must be an empty object. Registration takes effect only after the subsequent nonempty tool-free final prose successfully commits, and includes that prose. A fresh context replays only committed player inputs and final narratives after this boundary, so save still-needed outcomes before registration. Consolidation and maintenance do not require this tool. Do not advance the story to register a checkpoint; registration neither switches context nor ends an in-world event. Further tool calls may follow registration; Runtime does not verify semantic completeness.",
@@ -4,6 +4,7 @@ import { randomUUID } from "node:crypto";
4
4
  import { link, mkdir, open, readFile, readdir, rename, rm, stat, } from "node:fs/promises";
5
5
  import { dirname, join } from "node:path";
6
6
  import { isDeepStrictEqual } from "node:util";
7
+ import { fictionGameplay } from "../../protocol/gameplay.js";
7
8
  import { ContentWorkspace } from "../content/ContentWorkspace.js";
8
9
  import { contentTreeFingerprint } from "../content/ContentTreeFingerprint.js";
9
10
  import { isPlayPresetBinding, } from "../play/FileNativePlayPresetStore.js";
@@ -447,7 +448,9 @@ function migrateLegacySession(value, applyOutcome) {
447
448
  createdAt: value.createdAt,
448
449
  updatedAt: value.updatedAt,
449
450
  creationRequestId: `legacy:${value.sessionId}`,
450
- bootstrap: compileSettingImprovementLegacyCurrentTreeBootstrap(structuredClone(value.bootstrap), value.locale, settingImprovementToolDefinitions(value.locale)),
451
+ bootstrap: compileSettingImprovementLegacyCurrentTreeBootstrap(structuredClone(value.bootstrap), value.locale,
452
+ // Released sessions predate gameplay, and a package's mode is fixed, so they are fiction.
453
+ settingImprovementToolDefinitions(value.locale, fictionGameplay)),
451
454
  modelBinding: structuredClone(value.modelBinding),
452
455
  ...(value.playPreset === undefined
453
456
  ? {}
@@ -2,7 +2,9 @@ import { isPackageFollowupControlPath } from "../content/PackageFollowups.js";
2
2
  import { renderWorldMaintenanceReport } from "../prompt/WorldMaintenanceReport.js";
3
3
  import { listWorldDocuments as listQueryableWorldDocuments } from "../prompt/WorldMaintenanceReport.js";
4
4
  import { defaultAppLocale } from "../../protocol/appPreferences.js";
5
+ import { gameplayLabel, gameplayPath, readGameplay, } from "../../protocol/gameplay.js";
5
6
  import { isScalar, isSeq, parseDocument, stringify } from "yaml";
7
+ import { tabletopSchemeReceipt } from "../play/TabletopRules.js";
6
8
  import { inspectContentPackageCurrentTree } from "../content/FileNativeContentTree.js";
7
9
  import { worldMaterialCoverage } from "../prompt/WorldMaterialCoverage.js";
8
10
  import { WorldDocumentStore, } from "../world/WorldDocumentStore.js";
@@ -60,7 +62,23 @@ export const settingAuthorContractExamples = {
60
62
  emptyPlayerViews: emptyPlayerViewsExample,
61
63
  playerViews: playerViewsExample,
62
64
  };
63
- export function settingImprovementRuntimeContract(locale) {
65
+ /**
66
+ * Model-facing mention of control/gameplay.json. Only a tabletop package may
67
+ * change the scheme, so fiction packages never see the file in their contract
68
+ * or tool text. Runtime validation of the path is unaffected.
69
+ */
70
+ function gameplayFileZh(tabletop) {
71
+ return tabletop
72
+ ? "、control/blocks/*.md 和 control/gameplay.json(只能修改跑团判定方案,玩法模式不可改)"
73
+ : " 和 control/blocks/*.md";
74
+ }
75
+ function gameplayFileEn(tabletop) {
76
+ return tabletop
77
+ ? ", control/blocks/*.md, and control/gameplay.json (only a tabletop resolution scheme may change)"
78
+ : ", and control/blocks/*.md";
79
+ }
80
+ export function settingImprovementRuntimeContract(locale, gameplay) {
81
+ const tabletop = gameplay.mode === "tabletop";
64
82
  return locale === "zh-CN"
65
83
  ? `# Runtime 设定完善对话契约
66
84
 
@@ -69,7 +87,7 @@ export function settingImprovementRuntimeContract(locale) {
69
87
  - 工具写入直接修改内容包当前树。每个完整 Provider 工具响应中的调用按顺序执行,成功改动在该响应结算时原子发布,发布后立即成为内容包权威,无需另一步确认。
70
88
  - 每个写工具调用独立结算,并按本响应中的调用顺序读取之前已接受的结果。某个调用失败只在对应工具结果中返回精确原因,不回滚同一响应内其他成功调用,也不阻止后续调用。Runtime 在写调用结算后自动运行内容树检查和真实 Prompt Preview,并把检查结果附在最后一个成功写调用的结果中。
71
89
  - 修改既有文件前必须完整读取它。setting_list/setting_search 的 cursor,以及 setting_read 的读取授权,只属于产生它们的当前树 revision;任何其他对话或手动编辑改变当前树后,必须重新读取再写。setting_read 总是完整返回精确文件,不截断、不分页。工具只暴露逻辑路径,不暴露宿主路径。
72
- - world/ 下只写 .yaml 或 .md 世界文档;专用文件只允许 opening.md、control/frame.yaml、control/player-views.yaml 和 control/blocks/*.md,以及 control/followups.yaml 和其中引用的 prompts/*.md、renderers/*.html、scripts/*.js、regex/*.yaml、assets/* 文本资源。人物、地点、规则与当前情境放在 world/,本世界特有的主持要求放在 control/。
90
+ - world/ 下只写 .yaml 或 .md 世界文档;专用文件只允许 opening.md、control/frame.yaml、control/player-views.yaml${gameplayFileZh(tabletop)},以及 control/followups.yaml 和其中引用的 prompts/*.md、renderers/*.html、scripts/*.js、regex/*.yaml、assets/* 文本资源。人物、地点、规则与当前情境放在 world/,本世界特有的主持要求放在 control/。
73
91
  - opening.md 是玩家看见的第一页,不得替玩家决定行动、台词或内心。会继续约束首次行动的事实也必须写入自然承载它的世界文档。
74
92
  - 新建 world 文档使用 setting_create:ref 由你提供,并同时提供路径、标题、摘要、别名与不含技术头的正文。ref 必须是唯一的 2~32 位小写 ASCII 短句柄;Runtime 自行完成技术存储。既有文档选择值会在读取时自动投影为对应的 @ref;跨文档引用和 control 中的文档选择只使用 @ref。
75
93
  - YAML 中指向整份文档的机械引用只写成单键 map,例如 { $ref: "@alex" };普通字符串中的 @alex 仍只是文字。frame 与 player-view selector 的 document 值也写成 "@alex",局部位置另用 locator 表达。
@@ -105,7 +123,7 @@ export function settingImprovementRuntimeContract(locale) {
105
123
  - Tool writes directly modify the content package's current tree. Calls in one complete Provider tool response execute in order; its successful changes publish atomically when that response settles, immediately become authoritative, and require no second confirmation.
106
124
  - Every write tool call settles independently and sees earlier accepted calls in response order. A failure returns its precise cause only in that call's result, does not roll back successful siblings, and does not stop later calls. Runtime automatically runs content-tree checks and a real Prompt Preview after writes and appends that review to the last successful write result.
107
125
  - Read an existing file completely before changing it. Cursors from setting_list and setting_search, and read authorization from setting_read, belong only to the current-tree revision that produced them. setting_read always returns the complete exact file without truncation or pagination. Re-read after another conversation or a manual edit changes the current tree. Tools expose logical paths, never host paths.
108
- - World documents are .yaml or .md files under world/. Special writes are limited to opening.md, control/frame.yaml, control/player-views.yaml, and control/blocks/*.md, plus control/followups.yaml and its referenced prompts/*.md, renderers/*.html, scripts/*.js, regex/*.yaml and assets/* text resources. Put characters, places, rules, and the current situation under world/, and world-specific hosting guidance under control/.
126
+ - World documents are .yaml or .md files under world/. Special writes are limited to opening.md, control/frame.yaml, control/player-views.yaml${gameplayFileEn(tabletop)}, plus control/followups.yaml and its referenced prompts/*.md, renderers/*.html, scripts/*.js, regex/*.yaml and assets/* text resources. Put characters, places, rules, and the current situation under world/, and world-specific hosting guidance under control/.
109
127
  - opening.md is the first page shown to the player. Never decide the player's action, dialogue, or inner thoughts. Facts that constrain the first action must also live in the world document that naturally owns them.
110
128
  - Create a world document with setting_create. You provide its unique 2-to-32-character lowercase ASCII ref, path, title, summary, aliases, and body without a technical header; Runtime completes the technical storage. Existing document selectors are automatically projected to their @refs when read. Cross-document references and control selectors use only @refs.
111
129
  - A mechanical YAML reference to one whole document is a one-key map such as { $ref: "@alex" }; @alex inside an ordinary string is still only text. The document value in frame and player-view selectors is likewise "@alex", with any local position expressed separately by a locator.
@@ -134,8 +152,11 @@ export function settingImprovementRuntimeContract(locale) {
134
152
  - Runtime commits durable state and narrative. Write results that must survive the next action to their natural owner; put short-lived cross-object situations with no single owner in the current situation; leave details that do not need to remain current in committed narrative.
135
153
  - Passing mechanical checks does not make content discoverable during play. Whenever important information is created or reorganized, decide its natural owner, initial injection or discovery path, future update location, and player-visible projection together.`;
136
154
  }
137
- export function settingImprovementToolDefinitions(locale = defaultAppLocale) {
138
- const descriptions = locale === "zh-CN" ? toolDescriptionsZhCN : toolDescriptionsEn;
155
+ export function settingImprovementToolDefinitions(locale, gameplay) {
156
+ const tabletop = gameplay.mode === "tabletop";
157
+ const descriptions = locale === "zh-CN"
158
+ ? toolDescriptionsZhCN(tabletop)
159
+ : toolDescriptionsEn(tabletop);
139
160
  const schema = (properties, required) => ({
140
161
  type: "object",
141
162
  additionalProperties: false,
@@ -243,26 +264,26 @@ export function settingImprovementToolDefinitions(locale = defaultAppLocale) {
243
264
  },
244
265
  ];
245
266
  }
246
- const toolDescriptionsEn = {
267
+ const toolDescriptionsEn = (tabletop) => ({
247
268
  setting_list: "List the world root or a world/ subdirectory from the content package's current tree. The root also lists opening and control files. A cursor is valid only for the same query and current-tree revision.",
248
269
  setting_search: "Search literal source text in world documents in the content package's current tree. within may be world, a world/ directory or path, or @ref.",
249
270
  setting_read: "Read a complete world document by world/ path or @ref, or read a complete opening/control file by exact path. Existing document selectors are projected to @refs. The result is never truncated or paginated.",
250
271
  setting_create: "Create one world/ .yaml or .md document. Supply a unique lowercase ASCII ref, title, summary, aliases, and body without a technical header; Runtime completes the storage envelope. The created document is already fully read.",
251
- setting_write_file: "Replace a completely read world/ .yaml or .md document body while preserving its identity and metadata, or create/replace opening.md, control/frame.yaml, control/player-views.yaml, or control/blocks/*.md, plus control/followups.yaml and its referenced prompts/*.md, renderers/*.html, scripts/*.js, regex/*.yaml and assets/* text resources. To repair a damaged world document, also provide ref, title, summary, and aliases; Runtime preserves any recoverable storage identity. Create new world documents with setting_create.",
272
+ setting_write_file: `Replace a completely read world/ .yaml or .md document body while preserving its identity and metadata, or create/replace opening.md, control/frame.yaml, control/player-views.yaml, ${tabletop ? "control/blocks/*.md, or control/gameplay.json (only a tabletop resolution scheme may change)" : "or control/blocks/*.md"}, plus control/followups.yaml and its referenced prompts/*.md, renderers/*.html, scripts/*.js, regex/*.yaml and assets/* text resources. To repair a damaged world document, also provide ref, title, summary, and aliases; Runtime preserves any recoverable storage identity. Create new world documents with setting_create.`,
252
273
  setting_patch: 'Update a completely read YAML world document without rewriting unrelated content. locator is a non-empty path whose segments are map keys or zero-based array indexes. Use add for a missing map key or array index, replace for an existing node, append for the end of an existing array, and remove for an existing map key or array item. When title, summary, or aliases are stale, update all three together with op "set_metadata". Rewrite Markdown bodies with setting_write_file.',
253
274
  setting_move: "Move a completely read world document to a new world/ .yaml or .md logical path while preserving its identity and contents.",
254
275
  setting_delete: "Permanently delete a completely read world document from the content-package current tree. Runtime rejects deletion while currentSituation, a frame slot, a player-view selector, or another document's $ref still points to it, and reports every blocking location. Delete or redirect those references first.",
255
- };
256
- const toolDescriptionsZhCN = {
276
+ });
277
+ const toolDescriptionsZhCN = (tabletop) => ({
257
278
  setting_list: "列出内容包当前树的 world 根目录或 world/ 子目录;根目录同时列出 opening 和 control 专用文件。cursor 只对同一查询和当前树 revision 有效。",
258
279
  setting_search: "在内容包当前树的 world 文档中按原文字面搜索;within 可为 world、world/ 目录或路径或 @ref。",
259
280
  setting_read: "按 world/ 路径或 @ref 完整读取世界文档,或按精确路径完整读取 opening/control;既有文档选择值自动投影为 @ref。结果不会截断或分页。",
260
281
  setting_create: "创建一份 world/ 下的 .yaml 或 .md 文档;提供唯一的小写 ASCII ref、标题、摘要、别名和不含技术头的正文,Runtime 自行完成存储封装。创建成功的文档视为已经完整读取。",
261
- setting_write_file: "整份替换已完整读取的 world/ .yaml 或 .md 正文并保留身份和元信息,或创建/替换 opening.md、control/frame.yaml、control/player-views.yaml、control/blocks/*.md,以及 control/followups.yaml 和其中引用的 prompts/*.md、renderers/*.html、scripts/*.js、regex/*.yaml、assets/* 文本资源。修复损坏世界文档时同时提供 ref、title、summary、aliases,Runtime 会保留仍可恢复的存储身份。新建世界文档使用 setting_create。",
282
+ setting_write_file: `整份替换已完整读取的 world/ .yaml 或 .md 正文并保留身份和元信息,或创建/替换 opening.md、control/frame.yaml、control/player-views.yaml、control/blocks/*.md${tabletop ? "、control/gameplay.json(只能修改跑团判定方案,玩法模式不可改)" : ""},以及 control/followups.yaml 和其中引用的 prompts/*.md、renderers/*.html、scripts/*.js、regex/*.yaml、assets/* 文本资源。修复损坏世界文档时同时提供 ref、title、summary、aliases,Runtime 会保留仍可恢复的存储身份。新建世界文档使用 setting_create。`,
262
283
  setting_patch: '细粒度更新已完整读取的 YAML 世界文档,不重写无关内容。locator 是非空路径,每段可以是 map key 或从 0 开始的数组下标;add 新建 map key 或数组位置,replace 更新既有节点,append 追加既有数组,remove 删除既有 map key 或数组项。title、summary 或 aliases 过时时用 op "set_metadata" 整组更新三项。Markdown 正文用 setting_write_file 整份重写。',
263
284
  setting_move: "把已完整读取的世界文档移动到新的 world/ .yaml 或 .md 逻辑路径,并保留身份与内容。",
264
285
  setting_delete: "从内容包当前树永久删除一份已完整读取的 world 文档。若 currentSituation、frame slot、player-view selector 或其他文档的 $ref 仍指向它,Runtime 会拒绝并返回全部精确阻挡位置;请先删除或改向这些引用。",
265
- };
286
+ });
266
287
  export class SettingAuthoringTransaction {
267
288
  #baseFiles;
268
289
  #locale;
@@ -918,10 +939,12 @@ function writeOpaque(snapshot, call, reads, locale) {
918
939
  throw new SettingAuthoringError("Special-file writes accept only path and contents");
919
940
  const path = safePath(requiredString(call.arguments.path, "path"));
920
941
  if (!writableOpaquePath(path))
921
- throw new SettingAuthoringError(localized(locale, "Special-file writes accept only opening.md, control/frame.yaml, control/player-views.yaml, or control/blocks/*.md", "专用文件只允许写入 opening.md、control/frame.yaml、control/player-views.yaml 或 control/blocks/*.md"));
942
+ throw new SettingAuthoringError(localized(locale, "Special-file writes accept only opening.md, control/frame.yaml, control/player-views.yaml, control/blocks/*.md, or control/gameplay.json", "专用文件只允许写入 opening.md、control/frame.yaml、control/player-views.yaml、control/blocks/*.md 或 control/gameplay.json"));
922
943
  const authoredContents = requiredString(call.arguments.contents, "contents");
923
944
  assertNoLiteralUnicodeEscapes(authoredContents, locale);
924
945
  const contents = projectOpaqueDocumentIds(snapshot, path, authoredContents);
946
+ if (path === gameplayPath)
947
+ assertGameplayWriteKeepsMode(snapshot.files, contents, locale);
925
948
  const next = cloneFiles(snapshot.files);
926
949
  const existing = next.find((file) => file.path === path);
927
950
  if (existing !== undefined && !reads.opaquePaths.has(path))
@@ -938,16 +961,36 @@ function writeOpaque(snapshot, call, reads, locale) {
938
961
  });
939
962
  rebaseReads(reads, revised);
940
963
  reads.opaquePaths.add(path);
964
+ const gameplay = path === gameplayPath ? readGameplay([{ path, contents }]) : null;
941
965
  return {
942
966
  snapshot: revised,
943
- markdown: localized(locale, `# Current-tree write accepted\n\n${existing === undefined ? "Created" : "Updated"} ${path} in the content package's current tree. This file is already fully read; do not read it again unless a later decision needs Runtime's exact serialization.`, `# 当前树写入已接受\n\n已在内容包当前树中${existing === undefined ? "创建" : "更新"} ${path}。该文件已视为完整读取;除非后续判断依赖 Runtime 的精确序列化结果,否则不要再次读取。`),
967
+ markdown: [
968
+ localized(locale, `# Current-tree write accepted\n\n${existing === undefined ? "Created" : "Updated"} ${path} in the content package's current tree. This file is already fully read; do not read it again unless a later decision needs Runtime's exact serialization.`, `# 当前树写入已接受\n\n已在内容包当前树中${existing === undefined ? "创建" : "更新"} ${path}。该文件已视为完整读取;除非后续判断依赖 Runtime 的精确序列化结果,否则不要再次读取。`),
969
+ ...(gameplay === null
970
+ ? []
971
+ : [
972
+ localized(locale, `Current gameplay: ${gameplayLabel(gameplay, locale)}.`, `当前玩法:${gameplayLabel(gameplay, locale)}。`),
973
+ // Mid-conversation the model learns the new scheme's rules here (ADR-0037 append-only).
974
+ ...(gameplay.mode === "tabletop"
975
+ ? [tabletopSchemeReceipt(gameplay, locale)]
976
+ : []),
977
+ ]),
978
+ ].join("\n\n"),
944
979
  };
945
980
  }
981
+ /** The gameplay mode is fixed; a write may only keep it or change a tabletop scheme. */
982
+ function assertGameplayWriteKeepsMode(files, contents, locale) {
983
+ const before = readGameplay(files);
984
+ const after = readGameplay([{ path: gameplayPath, contents }]);
985
+ if (before.mode !== after.mode)
986
+ throw new SettingAuthoringError(localized(locale, "Gameplay mode is fixed; control/gameplay.json may change only the resolution scheme of a tabletop package", "玩法模式固定;control/gameplay.json 只能修改跑团的判定方案,不能在互动式小说与跑团之间切换"));
987
+ }
946
988
  function writableOpaquePath(path) {
947
989
  return (isPackageFollowupControlPath(path) ||
948
990
  path === "opening.md" ||
949
991
  path === "control/frame.yaml" ||
950
992
  path === "control/player-views.yaml" ||
993
+ path === gameplayPath ||
951
994
  /^control\/blocks\/[a-z0-9][a-z0-9/_-]*\.md$/u.test(path));
952
995
  }
953
996
  function assertWorldWritesAuthorized(snapshotId, reads, changes, locale) {
@@ -231,11 +231,12 @@ export class SettingImprovementSession {
231
231
  const package_ = await this.#content.readCurrentTreeContentPackage(packageId);
232
232
  const bootstrap = this.#compiler.compileSettingImprovement({
233
233
  contentPackageTitle: package_.title,
234
- runtimeContract: settingImprovementRuntimeContract(locale),
234
+ gameplay: package_.gameplay,
235
+ runtimeContract: settingImprovementRuntimeContract(locale, package_.gameplay),
235
236
  authorPrompt: settingImprovementPromptForBinding(playPreset, locale),
236
237
  playPreset,
237
238
  modelBinding: modelBinding,
238
- tools: settingImprovementToolDefinitions(locale),
239
+ tools: settingImprovementToolDefinitions(locale, package_.gameplay),
239
240
  });
240
241
  return { bootstrap, playPreset };
241
242
  }
@@ -253,10 +254,11 @@ export class SettingImprovementSession {
253
254
  ]);
254
255
  const locale = this.#locale();
255
256
  const modelBinding = host.binding();
256
- const tools = settingImprovementToolDefinitions(locale);
257
+ const tools = settingImprovementToolDefinitions(locale, package_.gameplay);
257
258
  const bootstrap = this.#compiler.compileSettingImprovement({
258
259
  contentPackageTitle: package_.title,
259
- runtimeContract: settingImprovementRuntimeContract(locale),
260
+ gameplay: package_.gameplay,
261
+ runtimeContract: settingImprovementRuntimeContract(locale, package_.gameplay),
260
262
  authorPrompt: settingImprovementPromptForBinding(playPreset, locale),
261
263
  playPreset,
262
264
  modelBinding,
@@ -2,6 +2,7 @@ import { captureNarrativeOrigin, snapshotBackground, isHistoryBackground, } from
2
2
  import { FileNativeArtifactStore } from "../artifact/FileNativeArtifactStore.js";
3
3
  import { WorldExtensionRequests } from "../extension/WorldExtensionRequests.js";
4
4
  import { WorldExtensionControls, extensionDefinitions, } from "../extension/WorldExtensionControls.js";
5
+ import { assertSameGameplay, readGameplay, } from "../../protocol/gameplay.js";
5
6
  import { HistoryQuery } from "../history/HistoryQuery.js";
6
7
  import { exportStory } from "../history/StoryExport.js";
7
8
  import { PackageScriptPermissions } from "../extension/PackageScriptPermissions.js";
@@ -116,6 +117,13 @@ export class FileNativeWorldStore {
116
117
  throw new FileNativeWorldCreationError("world_corrupt", "Released world storage could not be migrated to the current format", error instanceof Error ? { cause: error } : undefined);
117
118
  }
118
119
  }
120
+ async gameplay(worldId) {
121
+ assertIdentity(worldId, "World ID");
122
+ await this.ensureCurrentStorage(worldId);
123
+ const root = join(this.#worldsRoot, worldId);
124
+ await readPublicationAt(root);
125
+ return readWorldGameplayAt(root);
126
+ }
119
127
  async readWorldSummary(worldId) {
120
128
  assertIdentity(worldId, "World ID");
121
129
  return readWorldSummaryAt(join(this.#worldsRoot, worldId));
@@ -472,6 +480,7 @@ export class FileNativeWorldStore {
472
480
  await this.ensureCurrentStorage(worldId);
473
481
  const root = join(this.#worldsRoot, worldId);
474
482
  await readPublicationAt(root);
483
+ assertControlGameplayUnchanged(await readTree(join(root, "control")), files);
475
484
  const staging = join(root, `runtime/.control-draft-${randomUUID()}`);
476
485
  await writeSurface(staging, "control", files);
477
486
  const final = join(root, "runtime/control-draft");
@@ -562,6 +571,7 @@ export class FileNativeWorldStore {
562
571
  }
563
572
  if (currentFingerprint !== input.expectedFingerprint)
564
573
  throw new FileNativeWorldCreationError("operation_conflict", "World control changed after this revision epoch opened");
574
+ assertControlGameplayUnchanged(current, input.files);
565
575
  await rm(stagingRoot, { recursive: true, force: true });
566
576
  await rm(previousPath, { recursive: true, force: true });
567
577
  await writeSurface(stagingRoot, "control", input.files);
@@ -618,6 +628,7 @@ export class FileNativeWorldStore {
618
628
  throw new FileNativeWorldCreationError("operation_conflict", "World control is frozen by a running attempt");
619
629
  const preview = await this.previewControlDraft(worldId, prompt);
620
630
  const root = join(this.#worldsRoot, worldId);
631
+ assertControlGameplayUnchanged(await readTree(join(root, "control")), await readTree(join(root, "runtime/control-draft")));
621
632
  const draft = join(root, "runtime/control-draft");
622
633
  const replacement = join(root, `runtime/.control-apply-${randomUUID()}`);
623
634
  await rename(draft, replacement);
@@ -2179,9 +2190,10 @@ async function readPublicationAt(root) {
2179
2190
  }
2180
2191
  async function readWorldSummaryAt(root, publication, serializeRebuild) {
2181
2192
  const published = publication ?? (await readPublicationAt(root));
2193
+ const gameplay = await readWorldGameplayAt(root);
2182
2194
  const { lastActivityAt, excerpt, playerTurns } = await readWorldActivity(root, serializeRebuild);
2183
2195
  const summary = {
2184
- ...toSummary(published),
2196
+ ...toSummary(published, gameplay),
2185
2197
  title: await readWorldTitleAt(root, published),
2186
2198
  lastActivityAt,
2187
2199
  excerpt,
@@ -2197,6 +2209,15 @@ async function readWorldTitleAt(root, published) {
2197
2209
  throw new FileNativeWorldCreationError("world_corrupt", "Local world shell is corrupt");
2198
2210
  return metadata.name;
2199
2211
  }
2212
+ /** Worlds copy the package's gameplay identity with control; its absence means interactive fiction. */
2213
+ async function readWorldGameplayAt(root) {
2214
+ try {
2215
+ return readGameplay(controlGameplayFiles(await readTree(join(root, "control"))));
2216
+ }
2217
+ catch (error) {
2218
+ throw new FileNativeWorldCreationError("world_corrupt", "World gameplay identity is corrupt", { cause: error });
2219
+ }
2220
+ }
2200
2221
  async function readJson(path) {
2201
2222
  return JSON.parse(await readFile(path, "utf8"));
2202
2223
  }
@@ -2210,13 +2231,26 @@ async function readOptionalJson(path) {
2210
2231
  throw error;
2211
2232
  }
2212
2233
  }
2213
- function toSummary(publication) {
2234
+ function toSummary(publication, gameplay) {
2214
2235
  return {
2215
2236
  worldId: publication.worldId,
2216
2237
  title: publication.title,
2217
2238
  parentEndpoint: publication.parentEndpoint,
2239
+ gameplay,
2218
2240
  };
2219
2241
  }
2242
+ /** World control is a fixed mode and scheme: drafts, revisions and applies may not change either. */
2243
+ function assertControlGameplayUnchanged(current, next) {
2244
+ try {
2245
+ assertSameGameplay(controlGameplayFiles(current), controlGameplayFiles(next));
2246
+ }
2247
+ catch (error) {
2248
+ throw new FileNativeWorldCreationError("candidate_validation_failed", error instanceof Error ? error.message : "World gameplay is fixed", { cause: error });
2249
+ }
2250
+ }
2251
+ function controlGameplayFiles(files) {
2252
+ return files.map((file) => ({ ...file, path: `control/${file.path}` }));
2253
+ }
2220
2254
  const worldNamePattern = /^[^\r\n]{1,160}$/u;
2221
2255
  function validWorldName(name) {
2222
2256
  return worldNamePattern.test(name);
@@ -4,6 +4,7 @@ import { validAuthoringRequests, } from "../authoring/AuthoringRequestSnapshot.j
4
4
  import { createHash, randomUUID } from "node:crypto";
5
5
  import { mkdir, open, readFile, readdir, rename, rm } from "node:fs/promises";
6
6
  import { dirname, join, resolve } from "node:path";
7
+ import { gameplayPath } from "../../protocol/gameplay.js";
7
8
  import { contentTreeFingerprint } from "../content/ContentTreeFingerprint.js";
8
9
  import { isPlayPresetBinding, } from "../play/FileNativePlayPresetStore.js";
9
10
  const uuidV4Pattern = "[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}";
@@ -604,6 +605,7 @@ function validRevisionPath(path) {
604
605
  return (safe &&
605
606
  (isPackageFollowupControlPath(path) ||
606
607
  /^state\/.+\.(?:ya?ml|md)$/u.test(path) ||
608
+ path === gameplayPath ||
607
609
  path === "control/frame.yaml" ||
608
610
  path === "control/player-views.yaml" ||
609
611
  /^control\/blocks\/.+\.md$/u.test(path)));