narraeon 0.5.1 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,4 @@
1
+ import { historyUseGuidance } from "../../shared/history-use-guidance.js";
1
2
  import { defaultAppLocale, } from "../../protocol/appPreferences.js";
2
3
  /**
3
4
  * Runtime-owned prompt tool registry.
@@ -9,6 +10,8 @@ import { defaultAppLocale, } from "../../protocol/appPreferences.js";
9
10
  export const registeredRuntimeToolNames = [
10
11
  "state_list",
11
12
  "history_list",
13
+ "history_search",
14
+ "history_read",
12
15
  "context_search",
13
16
  "context_read",
14
17
  "world_patch",
@@ -19,7 +22,7 @@ export const registeredRuntimeToolNames = [
19
22
  "artifact_clear",
20
23
  ];
21
24
  /** Changes only when the executable Runtime tool universe or schemas change. */
22
- export const runtimeToolRegistryRevision = "runtime-tools-v8";
25
+ export const runtimeToolRegistryRevision = "runtime-tools-v9";
23
26
  export function defaultRuntimeToolDefinitionStrategy(provider) {
24
27
  return provider === "openai_responses"
25
28
  ? "native_allowed_subset"
@@ -95,17 +98,45 @@ function createToolDefinitions(locale) {
95
98
  }, ["parent"]),
96
99
  },
97
100
  history_list: {
98
- description: descriptions.history_list,
101
+ description: descriptions.history_list + " " + historyUseGuidance(locale),
99
102
  inputSchema: object({
100
- order: { enum: ["newest_first", "oldest_first"] },
101
- cursor: { type: ["string", "null"] },
103
+ before: string,
104
+ after: string,
102
105
  limit: { type: "integer", minimum: 1, maximum: 100 },
103
- }, ["order"]),
106
+ cursor: string,
107
+ }, []),
108
+ },
109
+ history_search: {
110
+ description: descriptions.history_search + " " + historyUseGuidance(locale),
111
+ inputSchema: object({
112
+ queries: {
113
+ type: "array",
114
+ minItems: 1,
115
+ maxItems: 5,
116
+ items: { type: "string", minLength: 1, maxLength: 256 },
117
+ },
118
+ match: { enum: ["any", "all"] },
119
+ order: { enum: ["newest_first", "oldest_first"] },
120
+ caseSensitive: { type: "boolean" },
121
+ after: string,
122
+ before: string,
123
+ limit: { type: "integer", minimum: 1, maximum: 50 },
124
+ cursor: string,
125
+ }, []),
126
+ },
127
+ history_read: {
128
+ description: descriptions.history_read + " " + historyUseGuidance(locale),
129
+ inputSchema: object({
130
+ latest: { type: "integer", minimum: 1, maximum: 21 },
131
+ ref: string,
132
+ before: { type: "integer", minimum: 0, maximum: 20 },
133
+ after: { type: "integer", minimum: 0, maximum: 20 },
134
+ }, []),
104
135
  },
105
136
  context_search: {
106
137
  description: descriptions.context_search,
107
138
  inputSchema: object({
108
- source: { enum: ["state", "history"] },
139
+ source: { const: "state" },
109
140
  query: { type: "string", minLength: 1, maxLength: 256 },
110
141
  caseSensitive: { type: "boolean" },
111
142
  within: string,
@@ -209,26 +240,39 @@ function createToolDefinitions(locale) {
209
240
  const toolDescriptions = {
210
241
  en: {
211
242
  world_checkpoint: "Declare that the necessary state maintenance for this turn is complete and suggest starting a fresh context. No arguments. Registration becomes effective only when this turn’s final tool-free response commits, including that response in the checkpoint. This is your declaration, not Runtime verification or an automatic context switch. Further tool calls are allowed before the final nonempty tool-free response.",
212
- state_list: "List document and state directory handles known to Runtime. parent must be @dir-/ for the state root or an @dir-* handle returned by an earlier state_list result; descend only through returned directory handles. Catalog directories declared by the frozen world frame remain listed and usable when empty. A cursor is valid only for the same state snapshot, parent, and limit. Pass returned document handles to context_read. This tool never lists committed history.",
213
- history_list: "List handles for committed history messages known to Runtime. order must be newest_first or oldest_first. A cursor is valid only for the same committed-history snapshot, order, and limit. Pass returned @history-message-* handles to context_read. This tool never lists the mutable state directory.",
214
- context_search: "Search literal source text in state or history. Zero matches means only that the supplied text had no literal match; it does not prove that a world fact does not exist. Player-visible narrative must not recount the search process. within accepts only an @document or @dir-* handle returned by Runtime.",
215
- context_read: "Read the complete content of an @document, @node, or @history-message-* handle previously returned by Runtime. The read heading, metadata boundaries, body boundaries, scope, and completion marker in the result are not source text. set_metadata may include only the fields that must change; Runtime preserves omitted metadata fields. Update the writable body between the boundaries with locators. YAML bodies omit the $document technical header; Markdown bodies begin at the document's level-one heading. Results are never truncated or paginated. Never pass file paths, natural-language names, or an invented world/... value.",
243
+ state_list: "List document and state directory handles known to Runtime. parent must be @dir-/ for the state root or an @dir-* handle from the initial directory index or an earlier state_list result; no preliminary listing is needed for an already supplied handle. Catalog directories declared by the frozen world frame remain listed and usable when empty. A cursor is valid only for the same state snapshot, parent, and limit. Pass returned document handles to context_read. This tool never lists committed history.",
244
+ history_list: "Browse committed history on the current timeline. Omit anchors for the latest page; use only before or after with a Runtime ref (including refs in injected history) for the immediately adjacent page, excluding the anchor. Every page is oldest to newest. limit defaults to 20 (1–100 messages). Previews are only the first 120 Unicode code points. Use independent earlierCursor/laterCursor with {cursor} alone; no first-query parameters on continuation. Cursors bind world, tool, query and immutable ordered history. After history_changed rerun the query. Opening messages are queryable. Read full originals with history_read; positions are snapshot locations, not identities or turns.",
245
+ history_search: "Search committed originals on the current timeline with queries: 1–5 nonempty literal strings (max 256 code points each); no query alias or semantic filters. match defaults to any, or all within one message. NFKC normalization always applies; caseSensitive defaults to false (locale-und case folding), normalized duplicate queries collapse. order defaults to newest_first, or oldest_first. limit defaults to 10 (1–50 matching messages). Optional after/before refs exclude timeline boundaries independently of order; after must precede before. Each result has at most 3 partial original fragments, query occurrence counts and complete-original length. Read a hit and nearby context with history_read. Continue with {cursor} alone; history_changed requires a new query.",
246
+ history_read: "Read complete committed originals on the current timeline, never summarized, truncated or body-paginated. Use {latest:N} alone (1–21 messages), or {ref,before,after} with defaults before=after=0 and sum at most 20; do not mix modes. Ref may come directly from Runtime prompt injections or tools without listing first. Windows are always oldest to newest, including the anchor. earlier/later are immediately outside this window and can be the next ref with before/after to avoid rereading. Boundaries and empty history are normal. Counts are messages, not turns; 21 long messages can produce large output.",
247
+ context_search: "Search literal source text in state documents. Use source=state; committed history uses history_search. Zero matches means only that the supplied text had no literal match; it does not prove that a world fact does not exist. Player-visible narrative must not recount the search process. within accepts only an @document or @dir-* handle returned by Runtime.",
248
+ context_read: "Read the complete content of an @document or @node handle previously returned by Runtime. The read heading, metadata boundaries, body boundaries, scope, and completion marker in the result are not source text. set_metadata may include only the fields that must change; Runtime preserves omitted metadata fields. Update the writable body between the boundaries with locators. YAML bodies omit the $document technical header; Markdown bodies begin at the document's level-one heading. Results are never truncated or paginated. Never pass file paths, natural-language names, or an invented world/... value.",
216
249
  world_patch: 'Update a document that has been read precisely or whose complete body was injected with write authorization. target must be an @short-ref. When title, summary, or aliases are stale, use set_metadata and include only the title, summary, or aliases that must change. At least one is required; Runtime preserves omitted fields from the current candidate document. A YAML edit uses locator:{yaml:["field","child"]}, for example {op:"replace",locator:{yaml:["status"]},value:"new value"}. Locator segments address map keys or a zero-based array index; remove deletes exactly the existing key or array item at its locator. A YAML value may reference a whole document only as {$ref:"@short-ref"}; the short reference must come from a Runtime list, read, or create result. Never invent a document id. If no handle is available, use ordinary text when semantically correct or call world_create first and use its returned @short-ref. To add an item to the end of an existing sequence, use append with the locator pointing to that sequence; add creates only a map key or list index that does not exist. A Markdown locator excludes the document level-one heading: {markdown:["Responsibilities"]} points exactly to ## Responsibilities, and replace_section.markdown must begin with the same heading at the same level. Use replace_preamble for text after the level-one heading and before the first level-two heading; send only that text. Use replace_body to replace the whole Markdown body and retain the original level-one heading. Success reports only whether the document changed and does not echo the body. Call context_read again only when a later decision depends on Runtime\'s exact serialized body or current metadata. Do not use path, JSON Pointer, set, or a file name.',
217
- world_create: 'Create a document inside a Runtime-known state directory. parent must be an @dir-* handle listed by state_list, such as @dir-/characters; catalog directories declared by the frozen world frame remain available when empty, and @dir-/ is the root. A syntactically valid but unknown directory is rejected. refHint is a lowercase ASCII short-reference hint, not a world/ path. A YAML body may reference a whole document only as {$ref:"@short-ref"}, and the short reference must come from a Runtime list, read, or create result. Never invent a document id.',
250
+ world_create: 'Create a document inside a Runtime-known state directory. parent must be an @dir-* handle supplied by the initial directory index or state_list, such as @dir-/characters; catalog directories declared by the frozen world frame remain available when empty, and @dir-/ is the root. A syntactically valid but unknown directory is rejected. refHint is a lowercase ASCII short-reference hint, not a world/ path. A YAML body may reference a whole document only as {$ref:"@short-ref"}, and the short reference must come from a Runtime list, read, or create result. Never invent a document id.',
218
251
  world_retire: "Retire or restore an exact state document without deleting its narrative record. target must be an @short-ref that was read precisely or injected completely. retired:true removes the document from future frame catalog injection but keeps it listed, searchable, readable, referenceable, and restorable; retired:false restores catalog participation. This changes catalog participation, not explicit full-document injection or character activity; use world_patch for ordinary location or field changes.",
219
252
  artifact_emit: "Submit an artifact declared in advance for this follow-up request. Supply only the output name and payload; Runtime fixes the channel, key, content type, renderer, retention policy, and authority meaning in the contract.",
220
253
  artifact_clear: "Clear the projection of an artifact that this follow-up declared in advance and explicitly allows to be cleared. The call cannot choose a channel, key, or any other output contract.",
221
254
  },
222
255
  "zh-CN": {
223
256
  world_checkpoint: "声明本轮必要状态已整理完成,并建议玩家在此开启全新上下文。参数为空对象。登记仅在本轮最终无工具响应提交后生效,检查点包含该响应。这是 AI 的整理声明,不是 Runtime 完整性认证,也不会自动切换上下文。最终非空且无工具调用的响应之前,仍可继续调用工具。",
224
- state_list: "列出 Runtime 已知的文档与状态目录句柄。状态根目录的 parent 使用 @dir-/;继续下级时只能使用先前 state_list 结果返回的 @dir-*。冻结世界 frame 声明的 catalog 目录即使为空,也会继续列出并可用。cursor 只对同一状态快照、parent 和 limit 有效。返回的文档句柄交给 context_read;本工具不列出已提交历史。",
225
- history_list: "列出 Runtime 已知的已提交历史消息句柄。order 必须是 newest_first 或 oldest_first;cursor 只对同一历史快照、order 和 limit 有效。返回的 @history-message-* 交给 context_read;本工具不列出可变状态目录。",
226
- context_search: "在 state 或 history 的原文字面中搜索。0 命中只表示给定文本没有字面命中,不证明世界事实不存在;玩家可见叙事不得复述搜索过程。within 只能使用 Runtime 已返回的 @文档或 @dir-* 句柄。",
227
- context_read: "完整读取 Runtime 先前返回的 @文档、@节点或 @history-message-* 句柄。结果中的读取标题、元信息边界、正文边界、范围和完整标记不属于源文;set_metadata 可以只提交需要改变的字段,Runtime 会保留未提供的元数据字段。中间的可写正文用 locator 更新。YAML 正文不含 $document 技术头,Markdown 正文从文档 # 一级标题开始。结果不会截断或分页。不要传文件路径、自然语言名称或自行拼造的 world/...。",
257
+ state_list: "列出 Runtime 已知的文档与状态目录句柄。状态根目录的 parent 使用 @dir-/;继续下级时使用初始目录索引或 state_list 返回的 @dir-*;已有句柄无需再次列目录确认。冻结世界 frame 声明的 catalog 目录即使为空,也会继续列出并可用。cursor 只对同一状态快照、parent 和 limit 有效。返回的文档句柄交给 context_read;本工具不列出已提交历史。",
258
+ history_list: "浏览当前时间线已提交历史。无锚点时取最新一页;before 或 after 只能选一个,取锚点紧邻前/后的一页且不含锚点。页内始终由旧到新。limit 默认20,整数1–100。预览仅含前120个Unicode码点;完整原文用history_read。earlierCursor/laterCursor独立翻页,续页只传{cursor},不可混用首次参数。游标绑定世界、工具、查询和有序历史快照;history_changed须重新查询。开场白可查询。提示词注入中的ref可直接使用,无需再次列举;位置不是身份或回合数。",
259
+ history_search: "搜索当前时间线已提交原文。queries必填:1–5个非空字面词,每词最多256个Unicode码点,不接受query别名或语义筛选。match默认any,all限于同一消息。始终NFKC规范化,caseSensitive默认false(locale-und大小写折叠),规范化重复词合并。order默认newest_first,可选oldest_first;limit默认10,整数1–50条命中消息。after/before始终按时间线先后排除边界,after必须早于before,与结果排序无关。每项最多3个部分原文片段、逐词命中次数及完整原文长度;可用history_read读取前后文。续页只传{cursor};history_changed须重新查询。",
260
+ history_read: "完整读取当前时间线已提交原文,无摘要、无截断、无正文分页。{latest:N}单独读取最近1–21条;或{ref,before,after},before/after默认0且合计最多20;两模式互斥。ref可直接使用Runtime提示词注入或工具结果的历史句柄,不必先列举。窗口始终由旧到新且包含锚点。earlier/later是窗口外紧邻句柄,可作为下一次ref并配before/after避免重复读取;边界与空历史正常。数量单位是消息而非回合;21条长消息仍可能产生大量输出。",
261
+ context_search: "在状态文档原文字面中搜索,source只能为state;已提交历史使用history_search。0 命中只表示给定文本没有字面命中,不证明世界事实不存在;玩家可见叙事不得复述搜索过程。within 只能使用 Runtime 已返回的 @文档或 @dir-* 句柄。",
262
+ context_read: "完整读取 Runtime 先前返回的 @文档或@节点句柄。结果中的读取标题、元信息边界、正文边界、范围和完整标记不属于源文;set_metadata 可以只提交需要改变的字段,Runtime 会保留未提供的元数据字段。中间的可写正文用 locator 更新。YAML 正文不含 $document 技术头,Markdown 正文从文档 # 一级标题开始。结果不会截断或分页。不要传文件路径、自然语言名称或自行拼造的 world/...。",
228
263
  world_patch: '更新已精确读取,或已随写入资格注入完整正文的文档。target 必须使用 @短引用;文档 title、summary 或 aliases 过时时使用 set_metadata,只提供需要改变的 title、summary 或 aliases。至少提供一项;未提供的字段由 Runtime 从当前候选文档保留。YAML edit 使用 locator:{yaml:["字段","子字段"]},例如 {op:"replace",locator:{yaml:["情况"]},value:"新值"}。locator 的每一段可以定位 map key 或从 0 开始的数组下标;remove 只删除 locator 精确指向的已有键或数组项。YAML value 需要引用整份文档时只能写 {$ref:"@短引用"},短引用必须来自 Runtime 的 list、read 或 create 结果;不得自行编造文档 id。没有可用句柄时,根据语义使用普通文本,或先 world_create 后使用其返回的 @短引用。向已存在的 sequence 末尾加一项必须使用 append 并把 locator 指向该 sequence;add 只创建尚不存在的 map key 或 list index。Markdown locator 不包含文档 # 一级标题:{markdown:["职责"]} 精确指向 ## 职责,replace_section.markdown 必须从同级同名标题开始。修改 # 标题下、第一个 ## 前的文字用 replace_preamble(只传该段文字);替换整个 Markdown 正文用 replace_body,且 markdown 必须保留原 # 一级标题。成功结果只报告文档是否发生变化,不回显正文;只有后续决策依赖 Runtime 序列化后的精确正文或当前元数据时才重新 context_read。不要使用 path、JSON Pointer、set 或文件名。',
229
- world_create: '在 Runtime 已知的状态目录中创建文档。parent 必须是 state_list 列出的 @dir-*,例如 @dir-/characters;冻结世界 frame 声明的 catalog 目录为空时仍然可用,根目录使用 @dir-/。只有句柄形式正确但 Runtime 并不知道的目录会被拒绝。refHint 是小写 ASCII 短引用,不要传 world/ 路径。YAML body 需要引用整份文档时只能写 {$ref:"@短引用"},且短引用必须来自 Runtime 的 list、read 或 create 结果;不得自行编造文档 id。',
264
+ world_create: '在 Runtime 已知的状态目录中创建文档。parent 必须是初始目录索引或 state_list 列出的 @dir-*,例如 @dir-/characters;冻结世界 frame 声明的 catalog 目录为空时仍然可用,根目录使用 @dir-/。只有句柄形式正确但 Runtime 并不知道的目录会被拒绝。refHint 是小写 ASCII 短引用,不要传 world/ 路径。YAML body 需要引用整份文档时只能写 {$ref:"@短引用"},且短引用必须来自 Runtime 的 list、read 或 create 结果;不得自行编造文档 id。',
230
265
  world_retire: "让一份精确状态文档退役或恢复,而不销毁叙事记录。target 必须是已精确读取或已完整注入的 @短引用。retired:true 会让文档不再进入后续 frame catalog 注入,但仍可列出、搜索、读取、引用和恢复;retired:false 恢复 catalog 参与。它只改变 catalog 参与,不取消显式全文注入、不冻结人物活动;普通位置或字段变化仍用 world_patch。",
231
266
  artifact_emit: "提交本次后置请求预先声明的产物。只能传 output name 与 payload;频道、key、内容类型、renderer、保存策略和权威含义由 Runtime contract 固定。",
232
267
  artifact_clear: "清除本次后置请求预先声明且允许 clear 的产物投影;不能选择频道、key 或其他输出契约。",
233
268
  },
234
269
  };
270
+ export function hasLegacyHistoryTools(tools) {
271
+ return tools.some(({ name, inputSchema }) => {
272
+ const schema = inputSchema;
273
+ return (name === "context_list" ||
274
+ (name === "history_list" && schema.properties?.order !== undefined) ||
275
+ (name === "context_search" &&
276
+ schema.properties?.source?.enum?.includes("history") === true));
277
+ });
278
+ }
@@ -1,3 +1,4 @@
1
+ import { isPromptMessageRole } from "../../shared/ordered-play-prompts.js";
1
2
  import { isWorldExtensionControl } from "../../protocol/worldExtensions.js";
2
3
  import { isWorldPromptMaintenance } from "../../protocol/worldMaintenance.js";
3
4
  /** Canonical validators for saved compiler output. Validate without projecting or rebuilding it. */
@@ -167,7 +168,11 @@ export function validLogicalMessages(value) {
167
168
  }
168
169
  function validLogicalMessage(value) {
169
170
  return (isRecord(value) &&
170
- hasExactKeys(value, ["role", "markdown", "blocks"]) &&
171
+ hasExactKeys(value, ["role", "markdown", "blocks"], ["messageRole", "promptId"]) &&
172
+ (value.messageRole === undefined ||
173
+ isPromptMessageRole(value.messageRole)) &&
174
+ (value.promptId === undefined ||
175
+ (typeof value.promptId === "string" && value.promptId.length > 0)) &&
171
176
  [
172
177
  "runtime_system",
173
178
  "author_instruction",
@@ -185,14 +190,19 @@ function validLogicalMessage(value) {
185
190
  }
186
191
  function validPromptProvider(value) {
187
192
  return (isRecord(value) &&
188
- hasExactKeys(value, ["protocol", "messages"], ["system"]) &&
193
+ hasExactKeys(value, ["protocol", "messages"], ["system", "preload"]) &&
194
+ (value.preload === undefined ||
195
+ (isRecord(value.preload) &&
196
+ hasExactKeys(value.preload, ["callId", "markdown"]) &&
197
+ value.preload.callId === "runtime_initial_world_context" &&
198
+ typeof value.preload.markdown === "string")) &&
189
199
  validProviderKind(value.protocol) &&
190
200
  (value.system === undefined ||
191
201
  (Array.isArray(value.system) && value.system.every(validSystemBlock))) &&
192
202
  Array.isArray(value.messages) &&
193
203
  value.messages.every((message) => isRecord(message) &&
194
204
  hasExactKeys(message, ["role", "content"]) &&
195
- (message.role === "system" || message.role === "user") &&
205
+ isPromptMessageRole(message.role) &&
196
206
  Object.hasOwn(message, "content")));
197
207
  }
198
208
  function validSystemBlock(value) {
@@ -0,0 +1,31 @@
1
+ export function stateDirectoryHandle(directory) {
2
+ if (directory === "")
3
+ return "@dir-/";
4
+ const encoded = directory.split("/").map(encodeURIComponent).join("/");
5
+ return `@dir-/${encoded}`;
6
+ }
7
+ export function parseStateDirectoryHandle(handle) {
8
+ if (handle === "@dir-/")
9
+ return "";
10
+ if (!handle.startsWith("@dir-/") || handle.length === "@dir-/".length)
11
+ return null;
12
+ try {
13
+ const directory = handle
14
+ .slice("@dir-/".length)
15
+ .split("/")
16
+ .map(decodeURIComponent)
17
+ .join("/");
18
+ if (directory
19
+ .split("/")
20
+ .some((segment) => segment === "" ||
21
+ segment === "." ||
22
+ segment === ".." ||
23
+ segment.includes("\\")) ||
24
+ stateDirectoryHandle(directory) !== handle)
25
+ return null;
26
+ return directory;
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ }
@@ -1,3 +1,4 @@
1
+ import { validLogicalMessages } from "../prompt/PromptCompilationCodec.js";
1
2
  import { isPackageFollowupControlPath } from "../content/PackageFollowups.js";
2
3
  import { validAuthoringRequests, } from "../authoring/AuthoringRequestSnapshot.js";
3
4
  import { createHash, randomUUID } from "node:crypto";
@@ -446,25 +447,6 @@ function validPromptCompilation(value) {
446
447
  isRecord(value.budget) &&
447
448
  isRecord(value.cache));
448
449
  }
449
- function validLogicalMessages(value) {
450
- return (Array.isArray(value) &&
451
- value.every((message) => isRecord(message) &&
452
- hasExactKeys(message, ["role", "markdown", "blocks"]) &&
453
- [
454
- "runtime_system",
455
- "author_instruction",
456
- "world_context",
457
- "player_input",
458
- "assistant",
459
- "tool",
460
- ].includes(String(message.role)) &&
461
- typeof message.markdown === "string" &&
462
- Array.isArray(message.blocks) &&
463
- message.blocks.every((block) => isRecord(block) &&
464
- hasExactKeys(block, ["source", "markdown"]) &&
465
- typeof block.source === "string" &&
466
- typeof block.markdown === "string")));
467
- }
468
450
  function validToolDefinitions(value) {
469
451
  return (Array.isArray(value) &&
470
452
  value.every((tool) => isRecord(tool) &&
@@ -0,0 +1,6 @@
1
+ /** Mechanical reading guidance shared by production prompts and tool help. */
2
+ export function historyUseGuidance(locale, legacy = false) {
3
+ return locale === "zh-CN"
4
+ ? `已有对话或注入原文足够接续时,不例行检索或重读。缺失信息会影响人物行为、重要承诺、因果或玩家选择时才检索${legacy ? ";仅使用本会话冻结的旧工具定义与参数定位及读取最近原文" : ";缺少最近上下文可直接 history_read {latest:4}"}。不记得原词时提出少量候选词,${legacy ? "用已声明旧历史搜索的单个 query 做字面搜索" : "用 history_search queries 的 any/all 字面搜索"},命中后按需完整读前后文${legacy ? "" : ";all 限于同一消息"}。零命中不证明事件未发生,可改词、${legacy ? "扩大字面范围或读相邻上下文" : "放宽 all 为 any 或读相邻上下文"}。原文已足以判断时停止,不为穷尽分页而检索;重要矛盾可继续追查。玩家原文可能只是行动尝试、意图或主张,结果须结合后续叙事;主持原文也可能包含角色谎言、猜测、梦境或回忆,role=narrator 不证明事实已确认。过去持有不代表现在持有,明确当前世界修订优先于旧叙事。主持读到的信息不自动成为场内角色的知识。注入历史是已发生材料,不是本轮新请求,不能重复执行最后一条历史玩家行动。读取完整原文可能很大,参考原文长度并按需小步扩展;无需固定 list→search→read 流程。`
5
+ : `Do not routinely search or reread when conversation or injected originals already suffice. Retrieve only when missing details affect behavior, important promises, causality or player choices${legacy ? "; use only this session's frozen legacy tool definitions and arguments to locate and read recent originals" : "; missing recent context can be read directly with history_read {latest:4}"}. When exact wording is unknown, propose a few candidate terms and ${legacy ? "use the declared legacy literal search with a single query" : "use history_search queries with any/all"}, then read surrounding originals as needed${legacy ? "" : "; all applies within one message"}. Zero literal matches do not prove an event never happened: change terms, ${legacy ? "widen the literal scope or read nearby context" : "relax all to any or read nearby context"}. Stop once originals support the decision, without exhausting pages; important contradictions may warrant further investigation. Player originals may be attempts, intentions or claims; check subsequent narrative for outcomes. Narrator originals may contain character lies, guesses, dreams or memories; role=narrator does not confirm truth. Past possession is not current possession; explicit current world corrections take precedence. Host information does not automatically become in-scene character knowledge. Injected history is already committed material, not the current request; never repeat a final historical player action. Full originals can be large: use length information and expand in small windows. No fixed list→search→read ritual is required.`;
6
+ }
@@ -1,5 +1,9 @@
1
+ import { historyUseGuidance } from "./history-use-guidance.js";
1
2
  import { defaultNarrationPromptForLocale } from "./default-play-prompts.js";
2
3
  import { defaultPresetHostFilesForLocale } from "./default-preset-host.js";
4
+ export function isPromptMessageRole(value) {
5
+ return value === "system" || value === "user" || value === "assistant";
6
+ }
3
7
  /** Application-owned references. Persist references; freeze resolved text in requests. */
4
8
  export function builtinPlayPrompts(locale) {
5
9
  const zh = locale === "zh-CN";
@@ -14,18 +18,22 @@ export function builtinPlayPrompts(locale) {
14
18
  body: zh
15
19
  ? `# 工具与响应结算
16
20
 
17
- 只可调用请求随附的工具。目录使用 Runtime 返回的 @dir-*;文档和历史使用返回的 @句柄。工具结果标明读取范围、完整性及 cursor;目录摘要不等于正文。材料覆盖中完整正文与精确读取授予对应范围的写入资格,界面绑定标注不授予额外权限。同一原生对话刷新提示时,仅在当前状态与旧读取凭据完全匹配时承接原精确范围,并合并本次注入授权;全新上下文不继承旧对话授权。
21
+ 只可调用请求随附的工具。目录使用预加载索引或工具返回的 @dir-*,无需重复列目录确认;文档和历史使用返回的 @句柄。工具结果标明读取范围、完整性及 cursor;目录摘要不等于正文。材料覆盖中完整正文与精确读取授予对应范围的写入资格,界面绑定标注不授予额外权限。初始世界材料只在全新上下文加载一次;后续成功工具调用与回执更新当前值和读取资格,不必重读自己刚成功写入的内容。全新上下文不继承旧对话授权。
18
22
 
19
23
  world_patch 的 YAML locator 可以包含 map key 和从零开始的数组下标;remove 删除一个精确位置。未提供的元数据保持原值。world_retire 从目录注入中退役文档,文档仍可读取、引用和恢复。工具响应的成功状态变化与后续最终叙事分别提交,后续失败不回滚已提交变化。成功写入回执表示当前值已改变;以真实回执的结算状态为准,模型文字不能提交世界。
20
24
 
21
- 包含工具调用的响应属于中间步,正文不作为最终叙事提交。收到全部工具结果后继续;没有工具调用的非空正文结束本次循环并由 Runtime 提交叙事。world_checkpoint 登记在随后最终叙事成功提交后生效,边界包含该叙事;登记后仍可继续工具调用。全新上下文的历史补充只包含检查点后的已提交玩家原文与最终叙事,排除开场白、工具和推理。`
25
+ 包含工具调用的响应属于中间步,正文不作为最终叙事提交。收到全部工具结果后继续;没有工具调用的非空正文结束本次循环并由 Runtime 提交叙事。world_checkpoint 登记在随后最终叙事成功提交后生效,边界包含该叙事;登记后仍可继续工具调用。全新上下文的历史补充只包含检查点后的已提交玩家原文与最终叙事,排除开场白、工具和推理。
26
+
27
+ ${historyUseGuidance(locale)}`
22
28
  : `# Tools and response settlement
23
29
 
24
- Use only attached tools. Directories use returned @dir-* handles; documents and history use returned @handles. Results identify read scope, completeness and cursor; directory summaries are not document bodies. Complete injected bodies and exact reads authorize writes within their corresponding scopes; player-view annotations grant no additional authority. Refreshing the same native conversation retains prior exact scopes only when the current state matches their proof, merging them with current injected authorization. A fresh context does not inherit old conversation authorization.
30
+ Use only attached tools. Directories use @dir-* handles from the preload or tool results; do not list them again just to confirm a handle; documents and history use returned @handles. Results identify read scope, completeness and cursor; directory summaries are not document bodies. Complete injected bodies and exact reads authorize writes within their corresponding scopes; player-view annotations grant no additional authority. Initial world materials load once per fresh context. Later successful tool calls and receipts update current values and read scopes; do not re-read merely to confirm your own successful writes. A fresh context does not inherit old conversation authorization.
25
31
 
26
32
  YAML world_patch locators accept map keys and zero-based array indexes; remove deletes one exact location. Omitted metadata remains unchanged. world_retire removes a document from catalog injection while keeping it readable, referenceable and restorable. Successful tool-response state changes and later final narrative commit separately; later failure does not roll back committed changes. Successful write receipts change current values; the actual receipt determines settlement, not model prose.
27
33
 
28
- Responses containing tool calls are intermediate steps; their text is not committed as final narrative. Continue after all tool results. A nonempty tool-free response ends this loop and Runtime commits its narrative. world_checkpoint takes effect after the subsequent final narrative commits, including that narrative in its boundary; further tool calls may follow registration. Fresh-context replay contains committed player originals and final narratives after the checkpoint, excluding the opening, tools and reasoning.`,
34
+ Responses containing tool calls are intermediate steps; their text is not committed as final narrative. Continue after all tool results. A nonempty tool-free response ends this loop and Runtime commits its narrative. world_checkpoint takes effect after the subsequent final narrative commits, including that narrative in its boundary; further tool calls may follow registration. Fresh-context replay contains committed player originals and final narratives after the checkpoint, excluding the opening, tools and reasoning.
35
+
36
+ ${historyUseGuidance(locale)}`,
29
37
  },
30
38
  {
31
39
  id: "play.style",