@dsh-agentic-roleplay/core 0.7.2 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +1 -1
  2. package/lib/authoring-tools-DNnx0Nts.js +3574 -0
  3. package/lib/authoring.js +295 -333
  4. package/lib/{child-CyCViUKa.js → child-D6mpkkCE.js} +130 -6
  5. package/lib/client.js +931 -415
  6. package/lib/client.js.map +1 -1
  7. package/lib/compaction.js +2 -2
  8. package/lib/doctor.js +2 -2
  9. package/lib/{gallery-BxZGOgMb.js → gallery-D9nG3C78.js} +2 -2
  10. package/lib/{generator-BFmSYvR8.js → generator-r1Czm7oi.js} +2 -2
  11. package/lib/helper.js +1 -1
  12. package/lib/{hooks-HnqXO8mM.js → hooks-BQCzgggH.js} +92 -8
  13. package/lib/images.js +4 -4
  14. package/lib/index.js +1326 -1638
  15. package/lib/{library-BGxPKs9a.js → library-zI-2tG7h.js} +59 -9
  16. package/lib/{lorebook-author-tools-D9RrMK5g.js → lorebook-author-tools-ywaYicwd.js} +7 -7
  17. package/lib/lorebook-authoring.js +4 -4
  18. package/lib/{narration-DvFBqmqe.js → narration-CnBlVure.js} +52 -8
  19. package/lib/orchestration.js +95 -18
  20. package/lib/{pack-jail-MPekqSuQ.js → pack-jail-5EJ-WYyW.js} +1274 -69
  21. package/lib/{packs-jowC-MN_.js → packs-Cv8hanXJ.js} +2 -2
  22. package/lib/{presenter-agent-DvZtnf0Q.js → presenter-agent-BSaMSd3G.js} +6 -6
  23. package/lib/{preset-VatN-845.js → preset-CWI3-0r1.js} +4 -3
  24. package/lib/{preset-author-tools-8kv1Glxe.js → preset-author-tools-BrJYa2cr.js} +7 -7
  25. package/lib/preset-authoring.js +5 -5
  26. package/lib/presets-MwOSMMyu.js +3998 -0
  27. package/lib/{reflection-CvOZGjmn.js → reflection-zSaMsjKj.js} +127 -127
  28. package/lib/{text-JbWfTHbr.js → text-BzudpQLS.js} +11 -1
  29. package/lib/{turn-guard-BvCs1VxB.js → turn-guard-Cv8pfHEA.js} +6 -2
  30. package/package.json +2 -2
  31. package/prompts/en/import/casting.md +14 -0
  32. package/prompts/en/import/classifier.md +9 -0
  33. package/prompts/en/import/finish-draft.md +1 -0
  34. package/prompts/en/import/generator.md +8 -0
  35. package/prompts/en/import/notice-repair.md +4 -0
  36. package/prompts/en/import/repair-again.md +3 -0
  37. package/prompts/en/import/roster.md +1 -0
  38. package/prompts/en/import/variables.md +1 -0
  39. package/prompts/en/roleplay/game-master.md +3 -0
  40. package/prompts/en/roleplay/standing.md +1 -0
  41. package/prompts/en/world/author.md +1 -1
  42. package/prompts/zh/import/casting.md +14 -0
  43. package/prompts/zh/import/classifier.md +9 -0
  44. package/prompts/zh/import/finish-draft.md +1 -0
  45. package/prompts/zh/import/generator.md +8 -0
  46. package/prompts/zh/import/notice-repair.md +4 -0
  47. package/prompts/zh/import/repair-again.md +3 -0
  48. package/prompts/zh/import/roster.md +1 -0
  49. package/prompts/zh/import/variables.md +1 -0
  50. package/prompts/zh/roleplay/game-master.md +3 -0
  51. package/prompts/zh/roleplay/standing.md +1 -0
  52. package/prompts/zh/world/author.md +1 -1
  53. package/lib/authoring-tools-q34iq3hW.js +0 -6140
  54. package/lib/route-DRTJ_vcA.js +0 -518
package/lib/authoring.js CHANGED
@@ -1,13 +1,15 @@
1
- import { G as findEntity, Pt as InvalidEditProblems, W as sourcesFor, Zt as authoredWorldOf, a as importHooks, c as isReviewing, ct as IMPORT_FOLDER, ft as readImportFolder, n as limitAuthoringAgents, o as importTools, q as itemise, zt as parseRelationEdit } from "./authoring-tools-q34iq3hW.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 { y as norm } from "./library-BGxPKs9a.js";
5
- 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-MPekqSuQ.js";
6
- import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-jowC-MN_.js";
7
- import { t as guardAuthoringTurns } from "./turn-guard-BvCs1VxB.js";
1
+ import "./access-DtOxFKBK.js";
2
+ import { Bt as authoredWorldOf, L as parseWorldInfoEdit, Z as checkWorld, a as importHooks, l as isReviewing, m as editsSince, n as limitAuthoringAgents, o as importTools } from "./authoring-tools-DNnx0Nts.js";
3
+ import { B as readWorldPrompt, K as IMPORT_FOLDER, L as PROSE_PROMPTS, R as deleteWorldPrompt, Tt as parseRelationEdit, V as writeWorldPrompt, bt as InvalidEditProblems, z as listWorldPrompts } from "./presets-MwOSMMyu.js";
4
+ import { H as parsePlotsFile, J as formatIssue, at as shippedPromptsDirectory } from "./hooks-BQCzgggH.js";
5
+ import { i as translator, r as languageOf } from "./text-BzudpQLS.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-5EJ-WYyW.js";
7
+ import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-Cv8hanXJ.js";
8
+ import { t as guardAuthoringTurns } from "./turn-guard-Cv8pfHEA.js";
8
9
  import { join, relative } from "node:path";
10
+ import { readFile, readdir } from "node:fs/promises";
11
+ import { createUserMessage } from "@deepseek-ai/dsh-llm";
9
12
  import { defineTool } from "@deepseek-ai/dsh-tools";
10
- import { readFile } from "node:fs/promises";
11
13
  import { isDeepStrictEqual } from "node:util";
12
14
  //#region src/host/authoring/read-tools.ts
13
15
  const output$4 = (value) => [{
@@ -44,6 +46,10 @@ var AuthoredWorldReader = class {
44
46
  })
45
47
  };
46
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
+ }
47
53
  };
48
54
  function listTool(reader, name, description, select, summarize) {
49
55
  return defineTool({
@@ -103,6 +109,26 @@ function authoredWorldReadTools(reader) {
103
109
  });
104
110
  }
105
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
+ }),
122
+ defineTool({
123
+ name: "world_check",
124
+ description: "Check the world as starting a story from it would: every file reads and everything that refers to something refers to something that is there. It names the problems of the first part of the world that has any (characters, factions, places, calendar, dice, items, lore, tracked values, triggers, plots), so run it again after fixing them to see whether another part has some. Run it before you say a world is done.",
125
+ parameters: {},
126
+ output: jsonOutput$3,
127
+ isConcurrencySafe: () => true,
128
+ async execute(_args, exec) {
129
+ return json$1(await checkWorld((await reader.read(exec)).record));
130
+ }
131
+ }),
106
132
  listTool(reader, "list_characters", "List authored characters with stable keys and concise identifying information.", (world) => world.characters, (entry) => ({
107
133
  key: entry.key,
108
134
  name: entry.name,
@@ -528,8 +554,22 @@ const keyParameter = {
528
554
  required: true,
529
555
  description: "Stable entity key."
530
556
  };
557
+ /** 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. */
558
+ const WORLD_INFO_FIELDS = [
559
+ "description",
560
+ "tags",
561
+ "rules",
562
+ "opening",
563
+ "alternateOpenings",
564
+ "startingTime",
565
+ "timeZone",
566
+ "version",
567
+ "authorName",
568
+ "authorUrl"
569
+ ];
531
570
  const AUTHORING_MUTATION_TOOLS = /* @__PURE__ */ new Set([
532
571
  "import_preset",
572
+ "edit_world_info",
533
573
  "create_world_element",
534
574
  "replace_world_element",
535
575
  "delete_world_element",
@@ -562,6 +602,38 @@ function plotDocument(value) {
562
602
  if (!parsed.ok) throw new InvalidEditProblems(parsed.issues.map(formatIssue));
563
603
  return parsed.value[0];
564
604
  }
605
+ /** The most problems a write reports back; `world_check` lists the rest. */
606
+ const REPORTED_PROBLEMS = 8;
607
+ /**
608
+ * A write is allowed to leave the world unfinished (a character first, its place next), so the check is advice, not a refusal: the assistant sees at once what its edit
609
+ * left open instead of finding out when a story is started.
610
+ */
611
+ function withWorldCheck(reader, tool) {
612
+ const run = tool.execute;
613
+ return {
614
+ ...tool,
615
+ async execute(args, exec) {
616
+ const done = await run(args, exec);
617
+ if (done === null || typeof done !== "object") return done;
618
+ const { record } = await reader.read(exec);
619
+ const check = await checkWorld(record);
620
+ if (check.ok) return {
621
+ ...done,
622
+ world_check: "ok: a story could start from this world"
623
+ };
624
+ const shown = check.problems.slice(0, REPORTED_PROBLEMS).map((problem) => `${problem.where}: ${problem.message}`);
625
+ return {
626
+ ...done,
627
+ world_check: {
628
+ ok: false,
629
+ still_open: shown,
630
+ more: check.problems.length - shown.length + check.more,
631
+ note: "Not an error of this edit; fix what the world still needs before the end of the turn (world_check lists all)."
632
+ }
633
+ };
634
+ }
635
+ };
636
+ }
565
637
  function authoredWorldWriteTools(reader) {
566
638
  return [
567
639
  defineTool({
@@ -631,6 +703,30 @@ function authoredWorldWriteTools(reader) {
631
703
  });
632
704
  }
633
705
  }),
706
+ defineTool({
707
+ name: "edit_world_info",
708
+ 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.`,
709
+ parameters: { changes: {
710
+ type: "json",
711
+ required: true,
712
+ description: "The fields to change, with their new values."
713
+ } },
714
+ output: jsonOutput,
715
+ async execute(args, exec) {
716
+ const { record } = await reader.read(exec);
717
+ const edit = parseWorldInfoEdit(args.changes);
718
+ const refused = Object.keys(edit).filter((key) => !WORLD_INFO_FIELDS.includes(key));
719
+ if (refused.length > 0) throw new InvalidEditProblems([`${refused.join(", ")} cannot be changed here: ${WORLD_INFO_FIELDS.join(", ")} can`]);
720
+ const info = await editWorldInfo(record.directory, edit);
721
+ await reader.refresh();
722
+ return {
723
+ action: "edited",
724
+ kind: "world info",
725
+ changed: Object.keys(edit),
726
+ info
727
+ };
728
+ }
729
+ }),
634
730
  defineTool({
635
731
  name: "edit_world_relationship",
636
732
  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.",
@@ -707,7 +803,7 @@ function authoredWorldWriteTools(reader) {
707
803
  });
708
804
  }
709
805
  })
710
- ];
806
+ ].map((tool) => withWorldCheck(reader, tool));
711
807
  }
712
808
  /**
713
809
  * 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.
@@ -762,6 +858,14 @@ async function authoringApproval(exec, next, reviewing = () => Promise.resolve(f
762
858
  }, remove ? void 0 : sizeOf(args["text"]))
763
859
  };
764
860
  }
861
+ if (exec.name === "edit_world_info") return {
862
+ kind: "ask",
863
+ reason: "edit the authored world's description, tags, opening or other world.json fields",
864
+ displayReason: withDetail({
865
+ en: "Edit what the world says about itself",
866
+ zh: "编辑世界对自身的描述"
867
+ }, await infoDetail(args["changes"], await options.info?.(exec.agent.session.id).catch(() => void 0)))
868
+ };
765
869
  const kind = typeof args["kind"] === "string" ? args["kind"] : exec.name === "edit_world_relationship" ? "relationship" : exec.name.endsWith("trigger") ? "trigger" : "plots";
766
870
  const key = typeof args["key"] === "string" ? args["key"] : "";
767
871
  const target = key === "" ? kind : `${kind} “${key}”`;
@@ -776,6 +880,19 @@ async function authoringApproval(exec, next, reviewing = () => Promise.resolve(f
776
880
  }, detail)
777
881
  };
778
882
  }
883
+ /** The fields of world.json the edit changes, each from what it is now to what it becomes. */
884
+ async function infoDetail(changes, before) {
885
+ let edit;
886
+ try {
887
+ edit = parseWorldInfoEdit(changes);
888
+ } catch {
889
+ return plain(changes);
890
+ }
891
+ return before === void 0 ? plain(edit) : changedFields(before, {
892
+ ...before,
893
+ ...edit
894
+ });
895
+ }
779
896
  function withDetail(headline, detail) {
780
897
  return detail === void 0 || detail.en === "" ? {
781
898
  en: `${headline.en}?`,
@@ -804,146 +921,20 @@ async function detailOf(exec, kind, key, current) {
804
921
  }
805
922
  }
806
923
  //#endregion
807
- //#region src/host/import/card-tools.ts
808
- /** The most of a piece one `card_read` returns; a long lorebook entry is read in turns. */
809
- const READ_CHARS = 6e3;
810
- const SNIPPET_CHARS = 240;
811
- const DEFAULT_HITS = 8;
812
- const MAX_HITS = 20;
813
- const baseId = (id) => id.replace(/#\d+$/, "");
814
- /** Everything the card holds, in the order the card has it. */
815
- function cardPieces(card, choices) {
816
- const read = new Set(itemise(card, choices).map((item) => baseId(item.id)));
817
- const field = (id, label, text) => text.trim() === "" ? [] : [{
818
- id,
819
- label,
820
- title: "",
821
- keys: [],
822
- text,
823
- used: read.has(id)
824
- }];
825
- return [
826
- ...field("field:description", "description", card.description),
827
- ...field("field:personality", "personality", card.personality),
828
- ...field("field:scenario", "scenario", card.scenario),
829
- ...field("field:example", "example messages", card.messageExample),
830
- ...field("field:first-message", "first message", card.firstMessage),
831
- ...card.alternateGreetings.flatMap((text, index) => field(`field:greeting-${index + 1}`, `alternate greeting ${index + 1}`, text)),
832
- ...field("field:creator-notes", "creator's notes", card.creatorNotes),
833
- ...field("field:system-prompt", "system prompt", card.systemPrompt),
834
- ...field("field:post-history", "post-history instructions", card.postHistoryInstructions),
835
- ...(card.book?.entries ?? []).filter((entry) => entry.content.trim() !== "").map((entry) => ({
836
- id: entry.id,
837
- label: entry.title === "" ? entry.id : `entry “${entry.title}”`,
838
- title: entry.title,
839
- keys: entry.keys,
840
- text: entry.content,
841
- used: read.has(entry.id),
842
- enabled: entry.enabled
843
- }))
844
- ];
845
- }
846
- async function optional(file) {
847
- try {
848
- return JSON.parse(await readFile(file, "utf8"));
849
- } catch (error) {
850
- if (error.code === "ENOENT") return void 0;
851
- throw error;
924
+ //#region src/host/import/update-tools.ts
925
+ const MAX_HUNKS = 10;
926
+ const MAX_PIECES = 60;
927
+ const PREVIEW_CHARS = 300;
928
+ /** 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. */
929
+ async function loreTitles(directory) {
930
+ const titles = /* @__PURE__ */ new Map();
931
+ for (const key of await readdir(join(directory, "lore")).catch(() => [])) {
932
+ const document = await readFile(join(directory, "lore", key, "lore.json"), "utf8").then((text) => JSON.parse(text), () => void 0);
933
+ if (typeof document?.title !== "string") continue;
934
+ const title = document.title.normalize("NFKC").trim().toLowerCase();
935
+ titles.set(title, [...titles.get(title) ?? [], key]);
852
936
  }
853
- }
854
- /** The card kept in a world's import folder, and what the import made of it. The tools exist as long as the card does. */
855
- async function readSource(directory, withRecords) {
856
- const folder = join(directory, IMPORT_FOLDER);
857
- let read;
858
- try {
859
- read = await readImportFolder(folder);
860
- } catch (error) {
861
- if (error.code === "ENOENT") throw new Error("this world has no source card: it was not imported from one, or its .import folder was removed");
862
- throw error;
863
- }
864
- const records = withRecords ? {
865
- classified: await optional(join(folder, "classification.json")),
866
- roster: await optional(join(folder, "roster.json")),
867
- report: await optional(join(folder, "report.json"))
868
- } : {};
869
- return {
870
- card: read.card,
871
- choices: read.choices,
872
- pieces: cardPieces(read.card, read.choices),
873
- records
874
- };
875
- }
876
- const rolesOf = (classified, id) => {
877
- if (classified === void 0) return [];
878
- return [...new Set(Object.entries(classified).filter(([key]) => baseId(key) === id).flatMap(([, entry]) => entry.roles))];
879
- };
880
- function snippet(text, at, length) {
881
- const start = Math.max(0, at - Math.floor((SNIPPET_CHARS - length) / 2));
882
- const end = Math.min(text.length, start + SNIPPET_CHARS);
883
- return `${start > 0 ? "…" : ""}${text.slice(start, end).replace(/\s+/g, " ")}${end < text.length ? "…" : ""}`;
884
- }
885
- function searchPieces(pieces, query, limit) {
886
- const phrase = query.trim().toLowerCase();
887
- if (phrase === "") return [];
888
- const words = [...new Set(phrase.split(/[\s,;,、]+/).filter((word) => word.length >= (/^[\x00-\x7f]+$/.test(word) ? 3 : 2)))];
889
- const count = (text, needle) => {
890
- let n = 0;
891
- let first = -1;
892
- for (let at = text.indexOf(needle); at >= 0; at = text.indexOf(needle, at + needle.length)) {
893
- n += 1;
894
- if (first < 0) first = at;
895
- }
896
- return {
897
- n,
898
- first
899
- };
900
- };
901
- const look = (text) => {
902
- const lowered = text.toLowerCase();
903
- const whole = count(lowered, phrase);
904
- if (whole.n > 0) return {
905
- matches: whole.n,
906
- score: whole.n * 4 + 100,
907
- at: whole.first,
908
- length: phrase.length
909
- };
910
- const found = words.map((word) => ({
911
- word,
912
- ...count(lowered, word)
913
- })).filter((entry) => entry.n > 0);
914
- if (found.length === 0) return void 0;
915
- const best = found.reduce((a, b) => a.first <= b.first ? a : b, found[0]);
916
- return {
917
- matches: found.reduce((sum, entry) => sum + entry.n, 0),
918
- score: found.length * 10 + found.reduce((sum, entry) => sum + entry.n, 0),
919
- at: best.first,
920
- length: best.word.length
921
- };
922
- };
923
- return pieces.flatMap((piece) => {
924
- const inText = look(piece.text);
925
- if (inText !== void 0) return [{
926
- piece,
927
- in: "text",
928
- matches: inText.matches,
929
- score: inText.score,
930
- snippet: snippet(piece.text, inText.at, inText.length)
931
- }];
932
- const head = [piece.title, ...piece.keys].filter((part) => part !== "").join(" · ");
933
- const inHead = look(head);
934
- return inHead === void 0 ? [] : [{
935
- piece,
936
- in: "title or keys",
937
- matches: inHead.matches,
938
- score: inHead.score - 50,
939
- snippet: `${piece.title === "" ? "" : `title: ${piece.title}`}${piece.keys.length === 0 ? "" : `${piece.title === "" ? "" : "; "}keys: ${piece.keys.join(", ")}`}`
940
- }];
941
- }).sort((a, b) => b.score - a.score).slice(0, limit).map(({ piece, matches, in: where, snippet: text }) => ({
942
- piece,
943
- matches,
944
- in: where,
945
- snippet: text
946
- }));
937
+ return titles;
947
938
  }
948
939
  const output = {
949
940
  schema: { type: "json" },
@@ -953,200 +944,164 @@ const output = {
953
944
  }]
954
945
  };
955
946
  const json = (value) => JSON.parse(JSON.stringify(value));
956
- const idOf = (exec) => {
957
- const chat = exec.agent?.session.id;
958
- const world = chat === void 0 ? void 0 : authoredWorldOf(chat);
959
- if (world === void 0) throw new Error("this tool is available only in a world authoring chat");
960
- return world;
961
- };
962
947
  /**
963
- * Read-only tools over the card a world was imported from, which stays in the world's `.import` folder: they work while that folder holds the card and say so when it does not.
964
- * `records` adds what the import made of the card (the role of each piece, who it was used for); it is off only when a test compares the agent with and without it.
948
+ * 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,
949
+ * 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.
965
950
  */
966
- function cardTools(worlds, options = {}) {
967
- const withRecords = options.records !== false;
968
- const source = async (exec) => {
969
- const id = idOf(exec);
951
+ function updateTools(worlds) {
952
+ const worldOf = async (exec) => {
953
+ const chat = exec.agent?.session.id;
954
+ const id = chat === void 0 ? void 0 : authoredWorldOf(chat);
955
+ if (id === void 0) throw new Error("this tool is available only in a world authoring chat");
970
956
  const record = await worlds.find(id);
971
957
  if (record === void 0) throw new Error(`the authored world "${id}" no longer exists`);
972
- return await readSource(record.directory, withRecords);
973
- };
974
- const find = (pieces, id) => {
975
- const found = pieces.find((piece) => piece.id === id);
976
- if (found === void 0) throw new Error(`the card has no piece "${id}": use an id from card_overview or card_search`);
977
- return found;
958
+ return record.directory;
978
959
  };
979
- return [
980
- defineTool({
981
- name: "card_overview",
982
- description: "The card this world was imported from, which is kept: its name, creator and tags, every piece of it (field, greeting or lorebook entry) with its size, and, from the import's own records, what each piece was taken to be and which characters, places and things were made from it. Start here when the person asks where something in the world came from.",
983
- parameters: {},
984
- output,
985
- isConcurrencySafe: () => true,
986
- async execute(_args, exec) {
987
- const { card, choices, pieces, records } = await source(exec);
988
- const madeFrom = /* @__PURE__ */ new Map();
989
- for (const entity of records.roster ?? []) for (const entry of originOf(card, choices, pieces, records, entity.name)) madeFrom.set(entry.piece, [...madeFrom.get(entry.piece) ?? [], entity.name]);
990
- const made = (id) => madeFrom.get(id) ?? [];
991
- return json({
992
- card: {
993
- name: card.name,
994
- creator: card.creator,
995
- version: card.characterVersion,
996
- tags: card.tags,
997
- format: card.sourceSpec,
998
- ignoredScripts: card.ignored.scripts
960
+ return [defineTool({
961
+ name: "card_diff",
962
+ 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).",
963
+ parameters: {},
964
+ output,
965
+ isConcurrencySafe: () => true,
966
+ async execute(_args, exec) {
967
+ const directory = await worldOf(exec);
968
+ const before = await readSource(directory, true, "current");
969
+ const after = await readSource(directory, false, "new");
970
+ const match = matchPieces(before.pieces, after.pieces);
971
+ const made = entitiesByPiece(before);
972
+ const piecesOf = /* @__PURE__ */ new Map();
973
+ for (const [piece, names] of made) for (const name of names) piecesOf.set(name, /* @__PURE__ */ new Set([...piecesOf.get(name) ?? [], piece]));
974
+ const lore = await loreTitles(directory);
975
+ const loreOf = (title) => lore.get(title.normalize("NFKC").trim().toLowerCase()) ?? [];
976
+ const onlyFrom = (piece) => (made.get(piece) ?? []).filter((name) => piecesOf.get(name)?.size === 1);
977
+ const changed = match.pairs.flatMap(({ before: was, after: now }) => {
978
+ const hunks = diffText(was.text, now.text);
979
+ const other = [
980
+ ...was.title === now.title ? [] : [`title: “${was.title}” → “${now.title}”`],
981
+ ...was.keys.join(", ") === now.keys.join(", ") ? [] : [`keys: ${was.keys.join(", ")} → ${now.keys.join(", ")}`],
982
+ ...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"]
983
+ ];
984
+ if (hunks?.length === 0 && other.length === 0) return [];
985
+ return [{
986
+ piece: now.id,
987
+ ...was.id === now.id ? {} : { wasPiece: was.id },
988
+ label: now.label,
989
+ madeInto: made.get(was.id) ?? [],
990
+ ...loreOf(was.title).length === 0 ? {} : { loreWithTheSameTitle: loreOf(was.title) },
991
+ characters: {
992
+ before: was.text.length,
993
+ after: now.text.length
999
994
  },
1000
- pieces: pieces.map((piece) => ({
1001
- id: piece.id,
1002
- label: piece.label,
1003
- characters: piece.text.length,
1004
- readByTheImport: piece.used,
1005
- ...piece.enabled === void 0 ? {} : { switchedOnInCard: piece.enabled },
1006
- ...withRecords ? {
1007
- takenToBe: rolesOf(records.classified, piece.id),
1008
- madeInto: made(piece.id)
1009
- } : {}
1010
- })),
1011
- ...records.roster === void 0 ? {} : { imported: records.roster.map((entity) => ({
1012
- name: entity.name,
1013
- kind: entity.kind,
1014
- aliases: entity.aliases,
1015
- playedByThePlayer: entity.player
1016
- })) },
1017
- ...records.report === void 0 ? {} : {
1018
- importNotes: records.report.notes,
1019
- leftOut: records.report.leftOut
995
+ ...hunks === void 0 ? { differences: "too long to compare here: read both versions with card_read" } : hunks.length === 0 ? {} : {
996
+ differences: hunks.slice(0, MAX_HUNKS),
997
+ ...hunks.length > MAX_HUNKS ? { moreDifferences: hunks.length - MAX_HUNKS } : {}
1020
998
  },
1021
- note: "The import's records are its own judgement and can be wrong or incomplete; check them against the text of the piece with card_read."
1022
- });
1023
- }
1024
- }),
1025
- defineTool({
1026
- name: "card_search",
1027
- description: "Searches everything the card says (fields, greetings, lorebook entries and their keys) for a name or phrase and returns the pieces that contain it, best first, each with a short snippet and whether it was found in the text or only in the title or keys of an entry. A hit is a pointer, not evidence: read the piece with card_read before you answer from it.",
1028
- parameters: {
1029
- query: {
1030
- type: "string",
1031
- required: true,
1032
- description: "A name or phrase to look for, in the card's own language."
1033
- },
1034
- limit: {
1035
- type: "number",
1036
- description: `How many pieces to return, at most ${MAX_HITS} (default ${DEFAULT_HITS}).`
1037
- }
1038
- },
1039
- output,
1040
- isConcurrencySafe: () => true,
1041
- async execute(args, exec) {
1042
- const { pieces } = await source(exec);
1043
- const limit = Math.min(MAX_HITS, Math.max(1, Math.floor(typeof args.limit === "number" && Number.isFinite(args.limit) ? args.limit : DEFAULT_HITS)));
1044
- const hits = searchPieces(pieces, args.query, limit);
1045
- return json({
1046
- query: args.query,
1047
- found: hits.length,
1048
- hits: hits.map(({ piece, matches, in: where, snippet: text }) => ({
1049
- piece: piece.id,
1050
- label: piece.label,
1051
- matches,
1052
- foundIn: where,
1053
- snippet: text
1054
- }))
1055
- });
1056
- }
1057
- }),
1058
- defineTool({
1059
- name: "card_read",
1060
- description: `The text of one piece of the card, word for word as the card has it (the card's own placeholders such as {{user}} included). A long piece is read in turns of ${READ_CHARS} characters: when "next" is given, call again with that offset.`,
1061
- parameters: {
1062
- piece: {
1063
- type: "string",
1064
- required: true,
1065
- description: "A piece id from card_overview or card_search, such as field:description or entry:3."
1066
- },
1067
- offset: {
1068
- type: "number",
1069
- description: "Where to start reading, in characters (default 0)."
1070
- }
1071
- },
1072
- output,
1073
- isConcurrencySafe: () => true,
1074
- async execute(args, exec) {
1075
- const { pieces } = await source(exec);
1076
- const piece = find(pieces, args.piece);
1077
- const from = Math.min(piece.text.length, Math.max(0, Math.floor(typeof args.offset === "number" && Number.isFinite(args.offset) ? args.offset : 0)));
1078
- const to = Math.min(piece.text.length, from + READ_CHARS);
1079
- return json({
999
+ ...other.length === 0 ? {} : { also: other }
1000
+ }];
1001
+ });
1002
+ const edits = await editsSince(directory);
1003
+ return json({
1004
+ card: cardChanges(before.card, after.card),
1005
+ changed: changed.slice(0, MAX_PIECES),
1006
+ ...changed.length > MAX_PIECES ? { moreChanged: changed.length - MAX_PIECES } : {},
1007
+ added: match.added.slice(0, MAX_PIECES).map((piece) => ({
1080
1008
  piece: piece.id,
1009
+ version: "new",
1081
1010
  label: piece.label,
1082
- ...piece.keys.length === 0 ? {} : { keys: piece.keys },
1083
- from,
1084
- to,
1085
- of: piece.text.length,
1086
- ...to < piece.text.length ? { next: to } : {},
1087
- text: piece.text.slice(from, to)
1088
- });
1089
- }
1090
- }),
1091
- defineTool({
1092
- name: "card_origin",
1093
- description: "Where a character, place, organisation or thing of this world came from: the pieces of the card the import read to make it (the pieces about it first, then those that only mention it), with what each was taken to be. For a name the import did not make anything of, the pieces of the card that mention it. Then read the pieces with card_read to answer from their text.",
1094
- parameters: { name: {
1095
- type: "string",
1096
- required: true,
1097
- description: "The name or an alias, as the world or the card has it."
1098
- } },
1099
- output,
1100
- isConcurrencySafe: () => true,
1101
- async execute(args, exec) {
1102
- const { card, choices, pieces, records } = await source(exec);
1103
- const entity = records.roster === void 0 ? void 0 : findEntity(records.roster, args.name);
1104
- if (entity === void 0 || records.classified === void 0) return json({
1105
- name: args.name,
1106
- madeByTheImport: false,
1107
- mentions: searchPieces(pieces, args.name, DEFAULT_HITS).map(({ piece, in: where, snippet: text }) => ({
1108
- piece: piece.id,
1109
- label: piece.label,
1110
- foundIn: where,
1111
- snippet: text
1112
- }))
1113
- });
1114
- return json({
1115
- name: entity.name,
1116
- kind: entity.kind,
1117
- aliases: entity.aliases,
1118
- madeByTheImport: true,
1119
- usedPieces: originOf(card, choices, pieces, records, entity.name).map((entry) => ({
1120
- piece: entry.piece,
1121
- label: entry.label,
1122
- how: entry.how,
1123
- takenToBe: rolesOf(records.classified, entry.piece)
1124
- }))
1125
- });
1126
- }
1127
- })
1128
- ];
1011
+ characters: piece.text.length,
1012
+ readByTheImport: piece.used,
1013
+ start: piece.text.slice(0, PREVIEW_CHARS)
1014
+ })),
1015
+ dropped: match.removed.slice(0, MAX_PIECES).map((piece) => ({
1016
+ piece: piece.id,
1017
+ version: "current",
1018
+ label: piece.label,
1019
+ wasReadByTheImport: piece.used,
1020
+ madeInto: made.get(piece.id) ?? [],
1021
+ madeOnlyFromIt: onlyFrom(piece.id),
1022
+ ...loreOf(piece.title).length === 0 ? {} : { loreWithTheSameTitle: loreOf(piece.title) }
1023
+ })),
1024
+ aboutTheWorld: worldFieldChanges(before, after),
1025
+ unchanged: match.pairs.length - changed.length,
1026
+ 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,
1027
+ 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."
1028
+ });
1029
+ }
1030
+ }), defineTool({
1031
+ name: "card_update_finish",
1032
+ 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.`,
1033
+ parameters: {},
1034
+ output,
1035
+ async execute(_args, exec) {
1036
+ const directory = await worldOf(exec);
1037
+ const outcome = await finishUpdate(directory, exec.signal === void 0 ? {} : { signal: exec.signal });
1038
+ return json({
1039
+ done: true,
1040
+ card: `${IMPORT_FOLDER}/card.json`,
1041
+ previous: join(IMPORT_FOLDER, "previous"),
1042
+ forgottenRecords: outcome.forgotten,
1043
+ pictures: outcome.pictures,
1044
+ ...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." },
1045
+ portrait: outcome.portrait,
1046
+ ...outcome.aboutTheWorld.length === 0 ? {} : {
1047
+ worldInfoToCheck: outcome.aboutTheWorld,
1048
+ 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."
1049
+ }
1050
+ });
1051
+ }
1052
+ })];
1129
1053
  }
1130
- /** The pieces an entity was made from, as the build chose them: the ones the survey said are about it, then those that name it. */
1131
- function originOf(card, choices, pieces, records, name) {
1132
- if (records.roster === void 0 || records.classified === void 0) return [];
1133
- const entity = findEntity(records.roster, name);
1134
- if (entity === void 0) return [];
1135
- const names = [entity.name, ...entity.aliases].map(norm);
1136
- const items = itemise(card, choices);
1137
- const chosen = sourcesFor(entity, items, records.classified);
1138
- const about = (id) => (records.classified?.[id]?.targets ?? []).some((target) => target.kind === entity.kind && names.includes(norm(target.name)));
1139
- const seen = /* @__PURE__ */ new Set();
1140
- return chosen.flatMap((item) => {
1141
- const id = baseId(item.id);
1142
- const piece = pieces.find((entry) => entry.id === id);
1143
- if (piece === void 0 || seen.has(id)) return [];
1144
- seen.add(id);
1145
- return [{
1146
- piece: id,
1147
- label: piece.label,
1148
- how: about(item.id) ? "about it" : "mentions it"
1149
- }];
1054
+ /** How many times an update turn that stopped before the update was finished is sent back to it. */
1055
+ const MAX_NUDGES = 1;
1056
+ /** The words of the message that starts an update, whatever the language it speaks. */
1057
+ const isUpdateRequest = (text) => text.includes("card_diff") && text.includes("card_update_finish");
1058
+ /**
1059
+ * 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
1060
+ * 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.
1061
+ */
1062
+ function updateHooks(ctx, worlds, languageOf$1) {
1063
+ const updating = /* @__PURE__ */ new Map();
1064
+ const nudges = /* @__PURE__ */ new Map();
1065
+ const authoring = (agent) => {
1066
+ const world = agent.session.header.origin === "subagent" ? void 0 : authoredWorldOf(agent.session.id);
1067
+ return world === void 0 ? void 0 : {
1068
+ chat: agent.session.id,
1069
+ world
1070
+ };
1071
+ };
1072
+ ctx.on("agent/pre-step", async (payload, next) => {
1073
+ const decision = await next();
1074
+ const here = authoring(payload.agent);
1075
+ if (decision.kind !== "enter" || payload.step !== 1 || here === void 0) return decision;
1076
+ const text = payload.messages.filter((message) => message.source.kind === "user").flatMap((message) => message.content.flatMap((block) => block.type === "text" ? [block.text] : [])).join("\n");
1077
+ if (isUpdateRequest(text)) {
1078
+ updating.set(here.chat, payload.turn);
1079
+ nudges.delete(here.chat);
1080
+ } else updating.delete(here.chat);
1081
+ return decision;
1082
+ });
1083
+ ctx.on("agent/turn-stopping", async ({ agent, turn }) => {
1084
+ const here = authoring(agent);
1085
+ if (here === void 0 || updating.get(here.chat) !== turn) return;
1086
+ const record = await worlds.find(here.world);
1087
+ if (record === void 0 || !await pendingUpdate(record.directory)) {
1088
+ updating.delete(here.chat);
1089
+ return;
1090
+ }
1091
+ const told = nudges.get(here.chat) ?? 0;
1092
+ if (told >= MAX_NUDGES) {
1093
+ updating.delete(here.chat);
1094
+ return;
1095
+ }
1096
+ nudges.set(here.chat, told + 1);
1097
+ const tr = translator(languageOf(languageOf$1(here.world)));
1098
+ agent.steer(createUserMessage({
1099
+ content: [{
1100
+ type: "text",
1101
+ 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.")
1102
+ }],
1103
+ source: { kind: "roleplay" }
1104
+ }));
1150
1105
  });
1151
1106
  }
1152
1107
  //#endregion
@@ -1178,9 +1133,11 @@ function apply(ctx) {
1178
1133
  for (const tool of worldPackTools(reader)) ctx.tools.register(tool);
1179
1134
  for (const tool of importTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
1180
1135
  for (const tool of cardTools(ctx.roleplayWorlds)) ctx.tools.register(tool);
1136
+ for (const tool of updateTools(ctx.roleplayWorlds)) ctx.tools.register(tool);
1181
1137
  for (const tool of presetTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
1182
1138
  for (const tool of translateTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
1183
1139
  importHooks(ctx, ctx.roleplayWorlds, prompting);
1140
+ updateHooks(ctx, ctx.roleplayWorlds, (world) => ctx.roleplayAuthoringLanguages.get(world));
1184
1141
  const reviewing = async (chat) => {
1185
1142
  const id = authoredWorldOf(chat);
1186
1143
  const record = id === void 0 ? void 0 : await ctx.roleplayWorlds.find(id);
@@ -1207,9 +1164,14 @@ function apply(ctx) {
1207
1164
  directory: record.directory
1208
1165
  }, kind, key);
1209
1166
  };
1167
+ const info = async (chat) => {
1168
+ const directory = await worldDirectory(chat);
1169
+ return directory === void 0 ? void 0 : await readWorldInfo(directory);
1170
+ };
1210
1171
  ctx.on("tools/pre-execute", (exec, next) => authoringApproval(exec, next, reviewing, {
1211
1172
  auto: () => ctx.roleplayImport.settings.approval === "auto",
1212
- current
1173
+ current,
1174
+ info
1213
1175
  }));
1214
1176
  for (const [name, order, id] of [[
1215
1177
  "WORLD_AUTHORING_PERSONA",