@dsh-agentic-roleplay/core 0.7.2 → 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.
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";
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";
7
8
  import { t as guardAuthoringTurns } from "./turn-guard-BvCs1VxB.js";
8
9
  import { join, relative } from "node:path";
10
+ import { createUserMessage } from "@deepseek-ai/dsh-llm";
9
11
  import { defineTool } from "@deepseek-ai/dsh-tools";
10
- import { readFile } from "node:fs/promises";
12
+ import { readFile, readdir } 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,16 @@ 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
+ }),
106
122
  listTool(reader, "list_characters", "List authored characters with stable keys and concise identifying information.", (world) => world.characters, (entry) => ({
107
123
  key: entry.key,
108
124
  name: entry.name,
@@ -528,8 +544,22 @@ const keyParameter = {
528
544
  required: true,
529
545
  description: "Stable entity key."
530
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
+ ];
531
560
  const AUTHORING_MUTATION_TOOLS = /* @__PURE__ */ new Set([
532
561
  "import_preset",
562
+ "edit_world_info",
533
563
  "create_world_element",
534
564
  "replace_world_element",
535
565
  "delete_world_element",
@@ -631,6 +661,30 @@ function authoredWorldWriteTools(reader) {
631
661
  });
632
662
  }
633
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
+ }),
634
688
  defineTool({
635
689
  name: "edit_world_relationship",
636
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.",
@@ -762,6 +816,14 @@ async function authoringApproval(exec, next, reviewing = () => Promise.resolve(f
762
816
  }, remove ? void 0 : sizeOf(args["text"]))
763
817
  };
764
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
+ };
765
827
  const kind = typeof args["kind"] === "string" ? args["kind"] : exec.name === "edit_world_relationship" ? "relationship" : exec.name.endsWith("trigger") ? "trigger" : "plots";
766
828
  const key = typeof args["key"] === "string" ? args["key"] : "";
767
829
  const target = key === "" ? kind : `${kind} “${key}”`;
@@ -776,6 +838,19 @@ async function authoringApproval(exec, next, reviewing = () => Promise.resolve(f
776
838
  }, detail)
777
839
  };
778
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
+ }
779
854
  function withDetail(headline, detail) {
780
855
  return detail === void 0 || detail.en === "" ? {
781
856
  en: `${headline.en}?`,
@@ -804,146 +879,20 @@ async function detailOf(exec, kind, key, current) {
804
879
  }
805
880
  }
806
881
  //#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;
852
- }
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;
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]);
863
894
  }
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
- }));
895
+ return titles;
947
896
  }
948
897
  const output = {
949
898
  schema: { type: "json" },
@@ -953,200 +902,164 @@ const output = {
953
902
  }]
954
903
  };
955
904
  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
905
  /**
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.
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.
965
908
  */
966
- function cardTools(worlds, options = {}) {
967
- const withRecords = options.records !== false;
968
- const source = async (exec) => {
969
- const id = idOf(exec);
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");
970
914
  const record = await worlds.find(id);
971
915
  if (record === void 0) throw new Error(`the authored world "${id}" no longer exists`);
972
- return await readSource(record.directory, withRecords);
916
+ return record.directory;
973
917
  };
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;
978
- };
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
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
999
952
  },
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
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 } : {}
1020
956
  },
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({
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) => ({
1080
966
  piece: piece.id,
967
+ version: "new",
1081
968
  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
- ];
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
+ })];
1129
1011
  }
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
- }];
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
+ };
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
+ }));
1150
1063
  });
1151
1064
  }
1152
1065
  //#endregion
@@ -1178,9 +1091,11 @@ function apply(ctx) {
1178
1091
  for (const tool of worldPackTools(reader)) ctx.tools.register(tool);
1179
1092
  for (const tool of importTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
1180
1093
  for (const tool of cardTools(ctx.roleplayWorlds)) ctx.tools.register(tool);
1094
+ for (const tool of updateTools(ctx.roleplayWorlds)) ctx.tools.register(tool);
1181
1095
  for (const tool of presetTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
1182
1096
  for (const tool of translateTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
1183
1097
  importHooks(ctx, ctx.roleplayWorlds, prompting);
1098
+ updateHooks(ctx, ctx.roleplayWorlds, (world) => ctx.roleplayAuthoringLanguages.get(world));
1184
1099
  const reviewing = async (chat) => {
1185
1100
  const id = authoredWorldOf(chat);
1186
1101
  const record = id === void 0 ? void 0 : await ctx.roleplayWorlds.find(id);
@@ -1207,9 +1122,14 @@ function apply(ctx) {
1207
1122
  directory: record.directory
1208
1123
  }, kind, key);
1209
1124
  };
1125
+ const info = async (chat) => {
1126
+ const directory = await worldDirectory(chat);
1127
+ return directory === void 0 ? void 0 : await readWorldInfo(directory);
1128
+ };
1210
1129
  ctx.on("tools/pre-execute", (exec, next) => authoringApproval(exec, next, reviewing, {
1211
1130
  auto: () => ctx.roleplayImport.settings.approval === "auto",
1212
- current
1131
+ current,
1132
+ info
1213
1133
  }));
1214
1134
  for (const [name, order, id] of [[
1215
1135
  "WORLD_AUTHORING_PERSONA",