@dsh-agentic-roleplay/core 0.7.1 → 0.7.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.
Files changed (29) hide show
  1. package/README.md +1 -1
  2. package/lib/{authoring-tools-BKltdiea.js → authoring-tools-CIsWbq0B.js} +197 -20
  3. package/lib/authoring.js +410 -32
  4. package/lib/client.js +679 -347
  5. package/lib/client.js.map +1 -1
  6. package/lib/doctor.js +1 -1
  7. package/lib/{gallery-BxZGOgMb.js → gallery-DmBZ2L5l.js} +2 -2
  8. package/lib/{generator-BFmSYvR8.js → generator-BmdoTIL2.js} +2 -2
  9. package/lib/{hooks-HnqXO8mM.js → hooks-C8eELrni.js} +2 -2
  10. package/lib/images.js +4 -4
  11. package/lib/index.js +111 -566
  12. package/lib/{library-BGxPKs9a.js → library-lVNf9qG_.js} +37 -4
  13. package/lib/{lorebook-author-tools-BAnUyRtS.js → lorebook-author-tools-BDOs4i5C.js} +6 -6
  14. package/lib/lorebook-authoring.js +3 -3
  15. package/lib/orchestration.js +8 -8
  16. package/lib/{pack-jail-DLGguGS3.js → pack-jail-DeTscGT2.js} +1255 -12
  17. package/lib/{packs-jowC-MN_.js → packs-CY8ms8v_.js} +2 -2
  18. package/lib/{presenter-agent-DvZtnf0Q.js → presenter-agent-cFR4sos3.js} +4 -4
  19. package/lib/{preset-author-tools-C26kj6t5.js → preset-author-tools-2m4BLtws.js} +6 -6
  20. package/lib/preset-authoring.js +4 -4
  21. package/lib/{preset-CXbC0NeU.js → preset-n4-j6k4S.js} +2 -2
  22. package/lib/{reflection-CvOZGjmn.js → reflection-CJB5s0ip.js} +6 -6
  23. package/lib/{route-DRTJ_vcA.js → route-C6SHz9j2.js} +2 -2
  24. package/lib/{text-JbWfTHbr.js → text-Cwl5s0j0.js} +3 -1
  25. package/package.json +2 -2
  26. package/prompts/en/import/finish-ok.md +1 -1
  27. package/prompts/en/world/procedure.md +1 -1
  28. package/prompts/zh/import/finish-ok.md +1 -1
  29. package/prompts/zh/world/procedure.md +1 -1
package/lib/authoring.js CHANGED
@@ -1,27 +1,31 @@
1
- import { At as InvalidEditProblems, Ft as parseRelationEdit, a as importHooks, c as isReviewing, n as limitAuthoringAgents, o as importTools, qt as authoredWorldOf } from "./authoring-tools-BKltdiea.js";
2
- import { C as readWorldPrompt, S as listWorldPrompts, b as PROSE_PROMPTS, w as writeWorldPrompt, x as deleteWorldPrompt } from "./route-DRTJ_vcA.js";
3
- import { G as formatIssue, V as parsePlotsFile, nt as shippedPromptsDirectory } from "./hooks-HnqXO8mM.js";
4
- import { C as readWorldEditor, F as loadWorldParts, H as translateTools, M as deleteTriggerDocument, N as readTriggerDocuments, P as writeTriggerDocument, R as presetTools, _ as editWorldPlots, a as deleteWorldPackFile, c as createAuthoredEntity, d as replaceAuthoredEntity, i as checkWorldPack, l as deleteAuthoredEntity, o as listWorldPacks, r as registerPackJail, s as AUTHORED_ENTITY_KINDS, u as readAuthoredEntityDocument, v as editWorldRelation } from "./pack-jail-DLGguGS3.js";
5
- import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-jowC-MN_.js";
1
+ import "./access-DtOxFKBK.js";
2
+ import { Dt as IMPORT_FOLDER, Lt as parseWorldInfoEdit, a as importHooks, d as editsSince, l as isReviewing, n as limitAuthoringAgents, nn as InvalidEditProblems, o as importTools, sn as parseRelationEdit, yn as authoredWorldOf } from "./authoring-tools-CIsWbq0B.js";
3
+ import { C as readWorldPrompt, S as listWorldPrompts, b as PROSE_PROMPTS, w as writeWorldPrompt, x as deleteWorldPrompt } from "./route-C6SHz9j2.js";
4
+ import { G as formatIssue, V as parsePlotsFile, nt as shippedPromptsDirectory } from "./hooks-C8eELrni.js";
5
+ import { i as translator, r as languageOf } from "./text-Cwl5s0j0.js";
6
+ import { $ as matchPieces, B as readWorldInfo, C as readWorldEditor, F as loadWorldParts, H as translateTools, K as finishUpdate, M as deleteTriggerDocument, N as readTriggerDocuments, P as writeTriggerDocument, Q as diffText, R as presetTools, Z as cardChanges, _ as editWorldPlots, a as deleteWorldPackFile, c as createAuthoredEntity, d as replaceAuthoredEntity, et as worldFieldChanges, i as checkWorldPack, l as deleteAuthoredEntity, nt as entitiesByPiece, o as listWorldPacks, q as pendingUpdate, r as registerPackJail, rt as readSource, s as AUTHORED_ENTITY_KINDS, tt as cardTools, u as readAuthoredEntityDocument, v as editWorldRelation, z as editWorldInfo } from "./pack-jail-DeTscGT2.js";
7
+ import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-CY8ms8v_.js";
6
8
  import { t as guardAuthoringTurns } from "./turn-guard-BvCs1VxB.js";
7
9
  import { join, relative } from "node:path";
10
+ import { createUserMessage } from "@deepseek-ai/dsh-llm";
8
11
  import { defineTool } from "@deepseek-ai/dsh-tools";
9
- import { readFile } from "node:fs/promises";
12
+ import { readFile, readdir } from "node:fs/promises";
13
+ import { isDeepStrictEqual } from "node:util";
10
14
  //#region src/host/authoring/read-tools.ts
11
- const output$3 = (value) => [{
15
+ const output$4 = (value) => [{
12
16
  type: "text",
13
17
  text: JSON.stringify(value, null, 2)
14
18
  }];
15
19
  const jsonOutput$3 = {
16
20
  schema: { type: "json" },
17
- render: (_args, value) => output$3(value)
21
+ render: (_args, value) => output$4(value)
18
22
  };
19
23
  const keyParameter$1 = {
20
24
  type: "string",
21
25
  required: true,
22
26
  description: "Stable key shown by the corresponding list tool."
23
27
  };
24
- const json = (value) => JSON.parse(JSON.stringify(value));
28
+ const json$1 = (value) => JSON.parse(JSON.stringify(value));
25
29
  /** Resolves every call from its authoring chat identity, then reads the files afresh. */
26
30
  var AuthoredWorldReader = class {
27
31
  worlds;
@@ -42,6 +46,10 @@ var AuthoredWorldReader = class {
42
46
  })
43
47
  };
44
48
  }
49
+ /** Lists the worlds again: the summaries (description, tags) come from `world.json`. */
50
+ async refresh() {
51
+ await this.worlds.list({ refresh: true });
52
+ }
45
53
  };
46
54
  function listTool(reader, name, description, select, summarize) {
47
55
  return defineTool({
@@ -51,7 +59,7 @@ function listTool(reader, name, description, select, summarize) {
51
59
  output: jsonOutput$3,
52
60
  isConcurrencySafe: () => true,
53
61
  async execute(_args, exec) {
54
- return json(select((await reader.read(exec)).state).map(summarize));
62
+ return json$1(select((await reader.read(exec)).state).map(summarize));
55
63
  }
56
64
  });
57
65
  }
@@ -65,7 +73,7 @@ function getTool(reader, name, description, select) {
65
73
  async execute(args, exec) {
66
74
  const found = select((await reader.read(exec)).state).find((entry) => entry.key === args.key);
67
75
  if (found === void 0) throw new Error(`there is no ${name.slice(4).replaceAll("_", " ")} with key "${args.key}"`);
68
- return json(found);
76
+ return json$1(found);
69
77
  }
70
78
  });
71
79
  }
@@ -81,7 +89,7 @@ function authoredWorldReadTools(reader) {
81
89
  async execute(_args, exec) {
82
90
  const { record, state } = await reader.read(exec);
83
91
  const document = JSON.parse(await readFile(join(record.directory, "world.json"), "utf8"));
84
- return json({
92
+ return json$1({
85
93
  id: record.summary.id,
86
94
  name: record.summary.name,
87
95
  description: record.summary.description,
@@ -101,6 +109,16 @@ function authoredWorldReadTools(reader) {
101
109
  });
102
110
  }
103
111
  }),
112
+ defineTool({
113
+ name: "get_world_info",
114
+ description: "Read what the world says about itself in world.json: name, description, tags, rules, the opening message and the alternate openings, author, version, time settings, and the preset, lorebooks, sampling and tool switches the person chose. edit_world_info changes the fields a card or an author is responsible for.",
115
+ parameters: {},
116
+ output: jsonOutput$3,
117
+ isConcurrencySafe: () => true,
118
+ async execute(_args, exec) {
119
+ return json$1(await readWorldInfo((await reader.read(exec)).record.directory));
120
+ }
121
+ }),
104
122
  listTool(reader, "list_characters", "List authored characters with stable keys and concise identifying information.", (world) => world.characters, (entry) => ({
105
123
  key: entry.key,
106
124
  name: entry.name,
@@ -160,7 +178,7 @@ function authoredWorldReadTools(reader) {
160
178
  isConcurrencySafe: () => true,
161
179
  async execute(args, exec) {
162
180
  const { record } = await reader.read(exec);
163
- return json(await readAuthoredEntityDocument({
181
+ return json$1(await readAuthoredEntityDocument({
164
182
  id: record.summary.id,
165
183
  directory: record.directory
166
184
  }, args.kind, args.key));
@@ -199,7 +217,7 @@ function authoredWorldReadTools(reader) {
199
217
  const { record } = await reader.read(exec);
200
218
  const found = (await readTriggerDocuments(record.directory)).find((entry) => entry["key"] === args.key);
201
219
  if (found === void 0) throw new Error(`there is no trigger with key "${args.key}"`);
202
- return json(found);
220
+ return json$1(found);
203
221
  }
204
222
  }),
205
223
  defineTool({
@@ -228,7 +246,7 @@ function authoredWorldReadTools(reader) {
228
246
  output: jsonOutput$3,
229
247
  isConcurrencySafe: () => true,
230
248
  async execute(args, exec) {
231
- return json((await reader.read(exec)).state.relations.filter((relation) => (args.kind === void 0 || relation.kind === args.kind) && (args.from === void 0 || relation.from.key === args.from) && (args.to === void 0 || relation.to.key === args.to)));
249
+ return json$1((await reader.read(exec)).state.relations.filter((relation) => (args.kind === void 0 || relation.kind === args.kind) && (args.from === void 0 || relation.from.key === args.from) && (args.to === void 0 || relation.to.key === args.to)));
232
250
  }
233
251
  })
234
252
  ];
@@ -236,13 +254,13 @@ function authoredWorldReadTools(reader) {
236
254
  //#endregion
237
255
  //#region src/host/authoring/pack-tools.ts
238
256
  const PACK_MUTATION_TOOLS = ["delete_world_pack_file"];
239
- const output$2 = (value) => [{
257
+ const output$3 = (value) => [{
240
258
  type: "text",
241
259
  text: JSON.stringify(value, null, 2)
242
260
  }];
243
261
  const jsonOutput$2 = {
244
262
  schema: { type: "json" },
245
- render: (_args, value) => output$2(value)
263
+ render: (_args, value) => output$3(value)
246
264
  };
247
265
  /** A path as the file tools take it: relative to the chat's folder when it has one, which is short and hard to mistype. */
248
266
  function relativeTo(exec, path) {
@@ -345,13 +363,13 @@ function worldPackTools(reader) {
345
363
  //#endregion
346
364
  //#region src/host/authoring/prompt-tools.ts
347
365
  const PROMPT_MUTATION_TOOLS = ["write_world_prompt", "delete_world_prompt"];
348
- const output$1 = (value) => [{
366
+ const output$2 = (value) => [{
349
367
  type: "text",
350
368
  text: JSON.stringify(value, null, 2)
351
369
  }];
352
370
  const jsonOutput$1 = {
353
371
  schema: { type: "json" },
354
- render: (_args, value) => output$1(value)
372
+ render: (_args, value) => output$2(value)
355
373
  };
356
374
  const idParameter = {
357
375
  type: "string",
@@ -439,14 +457,82 @@ function worldPromptTools(reader, shipped = shippedPromptsDirectory()) {
439
457
  ];
440
458
  }
441
459
  //#endregion
460
+ //#region src/host/authoring/approval-summary.ts
461
+ const MAX_FIELDS = 5;
462
+ function clip(value, max) {
463
+ const flat = (typeof value === "string" ? `“${value}”` : JSON.stringify(value) ?? "").replace(/\s+/g, " ");
464
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
465
+ }
466
+ const records = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
467
+ /** What a replacement changes, field by field at the top level: the person sees the edit, not just that there is one. */
468
+ function changedFields(before, after) {
469
+ if (!records(before) || !records(after)) return {
470
+ en: "",
471
+ zh: ""
472
+ };
473
+ const parts = [];
474
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])) {
475
+ if (isDeepStrictEqual(before[key], after[key])) continue;
476
+ if (!(key in before)) parts.push(`+${key} ${clip(after[key], 60)}`);
477
+ else if (!(key in after)) parts.push(`-${key}`);
478
+ else parts.push(`${key} ${clip(before[key], 40)} → ${clip(after[key], 40)}`);
479
+ }
480
+ if (parts.length === 0) return {
481
+ en: "no field changes",
482
+ zh: "没有字段变化"
483
+ };
484
+ const shown = parts.slice(0, MAX_FIELDS).join("; ");
485
+ const more = parts.length - MAX_FIELDS;
486
+ return {
487
+ en: more > 0 ? `${shown}; and ${more} more` : shown,
488
+ zh: more > 0 ? `${shown};另有 ${more} 项` : shown
489
+ };
490
+ }
491
+ /** A newly made document: its name and which fields it fills. */
492
+ function createdFields(document) {
493
+ if (!records(document)) return {
494
+ en: "",
495
+ zh: ""
496
+ };
497
+ const keys = Object.keys(document);
498
+ if (keys.length === 0) return {
499
+ en: "",
500
+ zh: ""
501
+ };
502
+ const name = typeof document["name"] === "string" ? `named ${clip(document["name"], 60)}, ` : "";
503
+ const zhName = typeof document["name"] === "string" ? `名为${clip(document["name"], 60)},` : "";
504
+ const listed = keys.slice(0, 8).join(", ") + (keys.length > 8 ? ", …" : "");
505
+ return {
506
+ en: `${name}fields: ${listed}`,
507
+ zh: `${zhName}字段:${listed}`
508
+ };
509
+ }
510
+ function sizeOf(text) {
511
+ if (typeof text !== "string") return {
512
+ en: "",
513
+ zh: ""
514
+ };
515
+ return {
516
+ en: `${text.length} characters, starting ${clip(text, 70)}`,
517
+ zh: `${text.length} 个字符,开头:${clip(text, 70)}`
518
+ };
519
+ }
520
+ function plain(value, max = 220) {
521
+ const text = clip(value, max);
522
+ return {
523
+ en: text,
524
+ zh: text
525
+ };
526
+ }
527
+ //#endregion
442
528
  //#region src/host/authoring/write-tools.ts
443
- const output = (value) => [{
529
+ const output$1 = (value) => [{
444
530
  type: "text",
445
531
  text: JSON.stringify(value, null, 2)
446
532
  }];
447
533
  const jsonOutput = {
448
534
  schema: { type: "json" },
449
- render: (_args, value) => output(value)
535
+ render: (_args, value) => output$1(value)
450
536
  };
451
537
  const kindParameter = {
452
538
  type: "string",
@@ -458,8 +544,22 @@ const keyParameter = {
458
544
  required: true,
459
545
  description: "Stable entity key."
460
546
  };
547
+ /** The fields of `world.json` the assistant changes: what the world says about itself. The name, the preset, the lorebooks, the sampling and the tool switches are the person's choices and stay theirs. */
548
+ const WORLD_INFO_FIELDS = [
549
+ "description",
550
+ "tags",
551
+ "rules",
552
+ "opening",
553
+ "alternateOpenings",
554
+ "startingTime",
555
+ "timeZone",
556
+ "version",
557
+ "authorName",
558
+ "authorUrl"
559
+ ];
461
560
  const AUTHORING_MUTATION_TOOLS = /* @__PURE__ */ new Set([
462
561
  "import_preset",
562
+ "edit_world_info",
463
563
  "create_world_element",
464
564
  "replace_world_element",
465
565
  "delete_world_element",
@@ -561,6 +661,30 @@ function authoredWorldWriteTools(reader) {
561
661
  });
562
662
  }
563
663
  }),
664
+ defineTool({
665
+ name: "edit_world_info",
666
+ description: `Change what the world says about itself in world.json: ${WORLD_INFO_FIELDS.join(", ")}. Give only the fields to change, as {"description": "...", "tags": ["..."], "opening": "...", "alternateOpenings": [{"title": "...", "text": "..."}]}: a list replaces the whole list, so read get_world_info first. The description is a short summary (a few sentences). An opening with lines spoken by characters cannot be edited as text. The name, preset, lorebooks, sampling and tool switches are the person's and cannot be changed here. Requires user approval.`,
667
+ parameters: { changes: {
668
+ type: "json",
669
+ required: true,
670
+ description: "The fields to change, with their new values."
671
+ } },
672
+ output: jsonOutput,
673
+ async execute(args, exec) {
674
+ const { record } = await reader.read(exec);
675
+ const edit = parseWorldInfoEdit(args.changes);
676
+ const refused = Object.keys(edit).filter((key) => !WORLD_INFO_FIELDS.includes(key));
677
+ if (refused.length > 0) throw new InvalidEditProblems([`${refused.join(", ")} cannot be changed here: ${WORLD_INFO_FIELDS.join(", ")} can`]);
678
+ const info = await editWorldInfo(record.directory, edit);
679
+ await reader.refresh();
680
+ return {
681
+ action: "edited",
682
+ kind: "world info",
683
+ changed: Object.keys(edit),
684
+ info
685
+ };
686
+ }
687
+ }),
564
688
  defineTool({
565
689
  name: "edit_world_relationship",
566
690
  description: "Create, update or remove one authored character relationship, knowledge edge, faction membership, faction social tie or map exit. To create: {\"create\": true, \"kind\", \"from\", \"to\", and the fields the kind needs (label for character and social, role for membership, description for exit, toKind for knowledge)}, with no key. To change: {\"kind\", \"key\", the fields to change}, the key copied exactly from list_relationships. To remove: {\"kind\", \"key\", \"remove\": true}. Requires user approval.",
@@ -642,11 +766,13 @@ function authoredWorldWriteTools(reader) {
642
766
  /**
643
767
  * Every change to the world files is put to the person, except in the turn that has just imported a card into the world: it reviews and corrects what it made.
644
768
  * @param reviewing - whether the authoring chat is in such a turn.
769
+ * @param options - `auto` is whether the person chose to have changes made without asking; `current` reads the document a replacement is about to replace, so the question can show what changes.
645
770
  */
646
- async function authoringApproval(exec, next, reviewing = () => Promise.resolve(false)) {
771
+ async function authoringApproval(exec, next, reviewing = () => Promise.resolve(false), options = {}) {
647
772
  if (!AUTHORING_MUTATION_TOOLS.has(exec.name) || exec.agent === void 0 || authoredWorldOf(exec.agent.session.id) === void 0) return await next();
648
773
  const args = exec.arguments;
649
- if (exec.name === "import_preset" && exec.agent !== void 0) return {
774
+ const auto = options.auto?.() === true;
775
+ if (exec.name === "import_preset" && exec.agent !== void 0 && !auto) return {
650
776
  kind: "ask",
651
777
  reason: "replace the authored world's narration and character-style prompts with ones made from the uploaded preset",
652
778
  displayReason: {
@@ -665,7 +791,7 @@ async function authoringApproval(exec, next, reviewing = () => Promise.resolve(f
665
791
  kind: "deny",
666
792
  reason: `an import may change only the prose prompts (${PROSE_PROMPTS.join(", ")}); "${String(args["id"])}" holds rules of the game and is left to the person`
667
793
  };
668
- if (importing) return await next();
794
+ if (importing || auto) return await next();
669
795
  if (pack) {
670
796
  const target = `file “${String(args["path"])}” of interface pack “${String(args["pack"])}”`;
671
797
  const remove = exec.name.startsWith("delete");
@@ -684,24 +810,257 @@ async function authoringApproval(exec, next, reviewing = () => Promise.resolve(f
684
810
  return {
685
811
  kind: "ask",
686
812
  reason: `${remove ? "delete" : "write"} authored world ${target}`,
687
- displayReason: {
688
- en: `${remove ? "Delete" : "Write"} ${target} in the world files?`,
689
- zh: `${remove ? "删除" : "写入"}世界文件中的${target}?`
690
- }
813
+ displayReason: withDetail({
814
+ en: `${remove ? "Delete" : "Write"} ${target} in the world files`,
815
+ zh: `${remove ? "删除" : "写入"}世界文件中的${target}`
816
+ }, remove ? void 0 : sizeOf(args["text"]))
691
817
  };
692
818
  }
819
+ if (exec.name === "edit_world_info") return {
820
+ kind: "ask",
821
+ reason: "edit the authored world's description, tags, opening or other world.json fields",
822
+ displayReason: withDetail({
823
+ en: "Edit what the world says about itself",
824
+ zh: "编辑世界对自身的描述"
825
+ }, await infoDetail(args["changes"], await options.info?.(exec.agent.session.id).catch(() => void 0)))
826
+ };
693
827
  const kind = typeof args["kind"] === "string" ? args["kind"] : exec.name === "edit_world_relationship" ? "relationship" : exec.name.endsWith("trigger") ? "trigger" : "plots";
694
828
  const key = typeof args["key"] === "string" ? args["key"] : "";
695
829
  const target = key === "" ? kind : `${kind} “${key}”`;
696
830
  const action = exec.name.startsWith("create") ? "Create" : exec.name.startsWith("delete") ? "Delete" : exec.name === "write_world_trigger" ? "Write" : "Edit";
831
+ const detail = await detailOf(exec, kind, key, options.current).catch(() => void 0);
697
832
  return {
698
833
  kind: "ask",
699
834
  reason: `${action.toLowerCase()} authored world ${target}`,
700
- displayReason: {
701
- en: `${action} ${target} in the world files?`,
702
- zh: `${action === "Create" ? "创建" : action === "Delete" ? "删除" : action === "Write" ? "写入" : "编辑"}世界文件中的${target}?`
835
+ displayReason: withDetail({
836
+ en: `${action} ${target} in the world files`,
837
+ zh: `${action === "Create" ? "创建" : action === "Delete" ? "删除" : action === "Write" ? "写入" : "编辑"}世界文件中的${target}`
838
+ }, detail)
839
+ };
840
+ }
841
+ /** The fields of world.json the edit changes, each from what it is now to what it becomes. */
842
+ async function infoDetail(changes, before) {
843
+ let edit;
844
+ try {
845
+ edit = parseWorldInfoEdit(changes);
846
+ } catch {
847
+ return plain(changes);
848
+ }
849
+ return before === void 0 ? plain(edit) : changedFields(before, {
850
+ ...before,
851
+ ...edit
852
+ });
853
+ }
854
+ function withDetail(headline, detail) {
855
+ return detail === void 0 || detail.en === "" ? {
856
+ en: `${headline.en}?`,
857
+ zh: `${headline.zh}?`
858
+ } : {
859
+ en: `${headline.en}: ${detail.en}`,
860
+ zh: `${headline.zh}:${detail.zh}`
861
+ };
862
+ }
863
+ /** What the change is, in a line the approval shows: the question is only useful if it says what is being decided. */
864
+ async function detailOf(exec, kind, key, current) {
865
+ const args = exec.arguments;
866
+ switch (exec.name) {
867
+ case "create_world_element": return createdFields(args["document"]);
868
+ case "replace_world_element": {
869
+ const before = exec.agent === void 0 ? void 0 : await current?.(exec.agent.session.id, kind, key);
870
+ return before === void 0 ? createdFields(args["document"]) : changedFields(before, args["document"]);
703
871
  }
872
+ case "edit_world_relationship": return plain(args["change"]);
873
+ case "replace_world_plots": return Array.isArray(args["plots"]) ? {
874
+ en: `${args["plots"].length} plots`,
875
+ zh: `${args["plots"].length} 条剧情`
876
+ } : void 0;
877
+ case "write_world_trigger": return createdFields(args["document"]);
878
+ default: return;
879
+ }
880
+ }
881
+ //#endregion
882
+ //#region src/host/import/update-tools.ts
883
+ const MAX_HUNKS = 10;
884
+ const MAX_PIECES = 60;
885
+ const PREVIEW_CHARS = 300;
886
+ /** The world's lore entries by normalised title: an entry the import made from a lorebook entry carries its title, and lore is not in the import's roster. */
887
+ async function loreTitles(directory) {
888
+ const titles = /* @__PURE__ */ new Map();
889
+ for (const key of await readdir(join(directory, "lore")).catch(() => [])) {
890
+ const document = await readFile(join(directory, "lore", key, "lore.json"), "utf8").then((text) => JSON.parse(text), () => void 0);
891
+ if (typeof document?.title !== "string") continue;
892
+ const title = document.title.normalize("NFKC").trim().toLowerCase();
893
+ titles.set(title, [...titles.get(title) ?? [], key]);
894
+ }
895
+ return titles;
896
+ }
897
+ const output = {
898
+ schema: { type: "json" },
899
+ render: (_args, value) => [{
900
+ type: "text",
901
+ text: JSON.stringify(value, null, 1)
902
+ }]
903
+ };
904
+ const json = (value) => JSON.parse(JSON.stringify(value));
905
+ /**
906
+ * The tools that bring a world up to date with a newer version of the card it was made from. `card_diff` is the starting point: what the card changed, worked out by code,
907
+ * with the import's records of what each piece made and the files the person has edited since; the assistant then edits with its ordinary tools and asks for those edits like any others.
908
+ */
909
+ function updateTools(worlds) {
910
+ const worldOf = async (exec) => {
911
+ const chat = exec.agent?.session.id;
912
+ const id = chat === void 0 ? void 0 : authoredWorldOf(chat);
913
+ if (id === void 0) throw new Error("this tool is available only in a world authoring chat");
914
+ const record = await worlds.find(id);
915
+ if (record === void 0) throw new Error(`the authored world "${id}" no longer exists`);
916
+ return record.directory;
917
+ };
918
+ return [defineTool({
919
+ name: "card_diff",
920
+ description: "What a newer version of the card this world was imported from changes. For each piece (field, greeting, lorebook entry) that changed, was added or was dropped: the sentences that differ, and the characters, places and things the import made from it, which are what may need to change. Also the files of the world that were edited since the import, and what the newer version changes about the card itself. Start here when asked to update the world from its card; read whole pieces with card_read (version current or new).",
921
+ parameters: {},
922
+ output,
923
+ isConcurrencySafe: () => true,
924
+ async execute(_args, exec) {
925
+ const directory = await worldOf(exec);
926
+ const before = await readSource(directory, true, "current");
927
+ const after = await readSource(directory, false, "new");
928
+ const match = matchPieces(before.pieces, after.pieces);
929
+ const made = entitiesByPiece(before);
930
+ const piecesOf = /* @__PURE__ */ new Map();
931
+ for (const [piece, names] of made) for (const name of names) piecesOf.set(name, /* @__PURE__ */ new Set([...piecesOf.get(name) ?? [], piece]));
932
+ const lore = await loreTitles(directory);
933
+ const loreOf = (title) => lore.get(title.normalize("NFKC").trim().toLowerCase()) ?? [];
934
+ const onlyFrom = (piece) => (made.get(piece) ?? []).filter((name) => piecesOf.get(name)?.size === 1);
935
+ const changed = match.pairs.flatMap(({ before: was, after: now }) => {
936
+ const hunks = diffText(was.text, now.text);
937
+ const other = [
938
+ ...was.title === now.title ? [] : [`title: “${was.title}” → “${now.title}”`],
939
+ ...was.keys.join(", ") === now.keys.join(", ") ? [] : [`keys: ${was.keys.join(", ")} → ${now.keys.join(", ")}`],
940
+ ...was.used === now.used ? [] : [now.used ? "the import read it before not; it is read now" : "the import read it before; it is left out now"]
941
+ ];
942
+ if (hunks?.length === 0 && other.length === 0) return [];
943
+ return [{
944
+ piece: now.id,
945
+ ...was.id === now.id ? {} : { wasPiece: was.id },
946
+ label: now.label,
947
+ madeInto: made.get(was.id) ?? [],
948
+ ...loreOf(was.title).length === 0 ? {} : { loreWithTheSameTitle: loreOf(was.title) },
949
+ characters: {
950
+ before: was.text.length,
951
+ after: now.text.length
952
+ },
953
+ ...hunks === void 0 ? { differences: "too long to compare here: read both versions with card_read" } : hunks.length === 0 ? {} : {
954
+ differences: hunks.slice(0, MAX_HUNKS),
955
+ ...hunks.length > MAX_HUNKS ? { moreDifferences: hunks.length - MAX_HUNKS } : {}
956
+ },
957
+ ...other.length === 0 ? {} : { also: other }
958
+ }];
959
+ });
960
+ const edits = await editsSince(directory);
961
+ return json({
962
+ card: cardChanges(before.card, after.card),
963
+ changed: changed.slice(0, MAX_PIECES),
964
+ ...changed.length > MAX_PIECES ? { moreChanged: changed.length - MAX_PIECES } : {},
965
+ added: match.added.slice(0, MAX_PIECES).map((piece) => ({
966
+ piece: piece.id,
967
+ version: "new",
968
+ label: piece.label,
969
+ characters: piece.text.length,
970
+ readByTheImport: piece.used,
971
+ start: piece.text.slice(0, PREVIEW_CHARS)
972
+ })),
973
+ dropped: match.removed.slice(0, MAX_PIECES).map((piece) => ({
974
+ piece: piece.id,
975
+ version: "current",
976
+ label: piece.label,
977
+ wasReadByTheImport: piece.used,
978
+ madeInto: made.get(piece.id) ?? [],
979
+ madeOnlyFromIt: onlyFrom(piece.id),
980
+ ...loreOf(piece.title).length === 0 ? {} : { loreWithTheSameTitle: loreOf(piece.title) }
981
+ })),
982
+ aboutTheWorld: worldFieldChanges(before, after),
983
+ unchanged: match.pairs.length - changed.length,
984
+ editedSinceTheImport: edits.edited === "unknown" ? "unknown: the import left no record of the files, so tell what you find in them before you change anything" : edits.edited === "no" ? "no" : edits.changes,
985
+ note: "Piece ids of changed pieces are those of the new card (wasPiece is the old id when it moved); an added piece is read with version new and a dropped one with version current, because the same id can name different pieces in the two cards. The import's records say what each old piece made; they can be wrong, so read the piece. A new piece has no record: decide from its text what it adds. A dropped piece: what was made only from it (madeOnlyFromIt) is what the new card no longer has; remove it with delete_world_element (the person is asked, and the folder goes to .trash) unless the person edited its file since the import (editedSinceTheImport) or something else in the world still needs it, and then keep it and say so. A lore entry with the dropped piece's title (loreWithTheSameTitle) was made from it; remove it too, and the knowledge of it that characters have. What a dropped piece made together with other pieces stays. aboutTheWorld lists what the card changed in what the world says about itself: read get_world_info and carry each over with edit_world_info (the description is a short summary of the world, a few sentences; tags are a few short words; opening is the greeting the world opens with; alternateOpenings are the card's other greetings), keeping what the person wrote when the card did not change that part."
986
+ });
987
+ }
988
+ }), defineTool({
989
+ name: "card_update_finish",
990
+ description: `Makes the newer card the card this world was made from, once the world has been brought up to date with it: the old card is kept in ${IMPORT_FOLDER}/previous, and what the world holds now is what later edits are measured against. Run it after your edits, and only then.`,
991
+ parameters: {},
992
+ output,
993
+ async execute(_args, exec) {
994
+ const directory = await worldOf(exec);
995
+ const outcome = await finishUpdate(directory, exec.signal === void 0 ? {} : { signal: exec.signal });
996
+ return json({
997
+ done: true,
998
+ card: `${IMPORT_FOLDER}/card.json`,
999
+ previous: join(IMPORT_FOLDER, "previous"),
1000
+ forgottenRecords: outcome.forgotten,
1001
+ pictures: outcome.pictures,
1002
+ ...outcome.pictures.droppedFromTheCard.length === 0 ? {} : { picturesTheCardNoLongerPointsTo: "These pictures in the image library came from addresses the newer card no longer has. They were left in the library; name them to the person in your report and do not delete them." },
1003
+ portrait: outcome.portrait,
1004
+ ...outcome.aboutTheWorld.length === 0 ? {} : {
1005
+ worldInfoToCheck: outcome.aboutTheWorld,
1006
+ instruction: "The card changed these things about the world itself. If you did not already carry each over with edit_world_info, do it now (or say in your report that you left it, and why). Report only what you actually changed."
1007
+ }
1008
+ });
1009
+ }
1010
+ })];
1011
+ }
1012
+ /** How many times an update turn that stopped before the update was finished is sent back to it. */
1013
+ const MAX_NUDGES = 1;
1014
+ /** The words of the message that starts an update, whatever the language it speaks. */
1015
+ const isUpdateRequest = (text) => text.includes("card_diff") && text.includes("card_update_finish");
1016
+ /**
1017
+ * An update turn that stops with the update still waiting is sent back once: models end such a turn on a change they found no place for, and the person then has neither the
1018
+ * rest of the update nor a report. A turn that stops again is let go, so a question to the person can still end it.
1019
+ */
1020
+ function updateHooks(ctx, worlds, languageOf$1) {
1021
+ const updating = /* @__PURE__ */ new Map();
1022
+ const nudges = /* @__PURE__ */ new Map();
1023
+ const authoring = (agent) => {
1024
+ const world = agent.session.header.origin === "subagent" ? void 0 : authoredWorldOf(agent.session.id);
1025
+ return world === void 0 ? void 0 : {
1026
+ chat: agent.session.id,
1027
+ world
1028
+ };
704
1029
  };
1030
+ ctx.on("agent/pre-step", async (payload, next) => {
1031
+ const decision = await next();
1032
+ const here = authoring(payload.agent);
1033
+ if (decision.kind !== "enter" || payload.step !== 1 || here === void 0) return decision;
1034
+ const text = payload.messages.filter((message) => message.source.kind === "user").flatMap((message) => message.content.flatMap((block) => block.type === "text" ? [block.text] : [])).join("\n");
1035
+ if (isUpdateRequest(text)) {
1036
+ updating.set(here.chat, payload.turn);
1037
+ nudges.delete(here.chat);
1038
+ } else updating.delete(here.chat);
1039
+ return decision;
1040
+ });
1041
+ ctx.on("agent/turn-stopping", async ({ agent, turn }) => {
1042
+ const here = authoring(agent);
1043
+ if (here === void 0 || updating.get(here.chat) !== turn) return;
1044
+ const record = await worlds.find(here.world);
1045
+ if (record === void 0 || !await pendingUpdate(record.directory)) {
1046
+ updating.delete(here.chat);
1047
+ return;
1048
+ }
1049
+ const told = nudges.get(here.chat) ?? 0;
1050
+ if (told >= MAX_NUDGES) {
1051
+ updating.delete(here.chat);
1052
+ return;
1053
+ }
1054
+ nudges.set(here.chat, told + 1);
1055
+ const tr = translator(languageOf(languageOf$1(here.world)));
1056
+ agent.steer(createUserMessage({
1057
+ content: [{
1058
+ type: "text",
1059
+ text: tr("The update from the newer card is not finished. Apply the changes that remain and call card_update_finish. A change you cannot make with your tools, or one you need the person to decide, goes in your report instead; then say what is left.")
1060
+ }],
1061
+ source: { kind: "roleplay" }
1062
+ }));
1063
+ });
705
1064
  }
706
1065
  //#endregion
707
1066
  //#region src/authoring.ts
@@ -731,9 +1090,12 @@ function apply(ctx) {
731
1090
  for (const tool of worldPromptTools(reader)) ctx.tools.register(tool);
732
1091
  for (const tool of worldPackTools(reader)) ctx.tools.register(tool);
733
1092
  for (const tool of importTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
1093
+ for (const tool of cardTools(ctx.roleplayWorlds)) ctx.tools.register(tool);
1094
+ for (const tool of updateTools(ctx.roleplayWorlds)) ctx.tools.register(tool);
734
1095
  for (const tool of presetTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
735
1096
  for (const tool of translateTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
736
1097
  importHooks(ctx, ctx.roleplayWorlds, prompting);
1098
+ updateHooks(ctx, ctx.roleplayWorlds, (world) => ctx.roleplayAuthoringLanguages.get(world));
737
1099
  const reviewing = async (chat) => {
738
1100
  const id = authoredWorldOf(chat);
739
1101
  const record = id === void 0 ? void 0 : await ctx.roleplayWorlds.find(id);
@@ -752,7 +1114,23 @@ function apply(ctx) {
752
1114
  const world = authoredWorldOf(chat);
753
1115
  return world === void 0 ? void 0 : ctx.roleplayAuthoringLanguages.get(world);
754
1116
  }, () => ctx.roleplayImport.settings.reasoning);
755
- ctx.on("tools/pre-execute", (exec, next) => authoringApproval(exec, next, reviewing));
1117
+ const current = async (chat, kind, key) => {
1118
+ const id = authoredWorldOf(chat);
1119
+ const record = id === void 0 ? void 0 : await ctx.roleplayWorlds.find(id);
1120
+ return record === void 0 ? void 0 : await readAuthoredEntityDocument({
1121
+ id: record.summary.id,
1122
+ directory: record.directory
1123
+ }, kind, key);
1124
+ };
1125
+ const info = async (chat) => {
1126
+ const directory = await worldDirectory(chat);
1127
+ return directory === void 0 ? void 0 : await readWorldInfo(directory);
1128
+ };
1129
+ ctx.on("tools/pre-execute", (exec, next) => authoringApproval(exec, next, reviewing, {
1130
+ auto: () => ctx.roleplayImport.settings.approval === "auto",
1131
+ current,
1132
+ info
1133
+ }));
756
1134
  for (const [name, order, id] of [[
757
1135
  "WORLD_AUTHORING_PERSONA",
758
1136
  ctx.systemPrompt.getSectionOrder("DEPLOYMENT_PERSONA_PREFIX"),