@dsh-agentic-roleplay/core 0.7.1 → 0.7.2

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,27 +1,29 @@
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";
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
2
  import { C as readWorldPrompt, S as listWorldPrompts, b as PROSE_PROMPTS, w as writeWorldPrompt, x as deleteWorldPrompt } from "./route-DRTJ_vcA.js";
3
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";
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";
5
6
  import { g as SURFACE_NAMES, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-jowC-MN_.js";
6
7
  import { t as guardAuthoringTurns } from "./turn-guard-BvCs1VxB.js";
7
8
  import { join, relative } from "node:path";
8
9
  import { defineTool } from "@deepseek-ai/dsh-tools";
9
10
  import { readFile } from "node:fs/promises";
11
+ import { isDeepStrictEqual } from "node:util";
10
12
  //#region src/host/authoring/read-tools.ts
11
- const output$3 = (value) => [{
13
+ const output$4 = (value) => [{
12
14
  type: "text",
13
15
  text: JSON.stringify(value, null, 2)
14
16
  }];
15
17
  const jsonOutput$3 = {
16
18
  schema: { type: "json" },
17
- render: (_args, value) => output$3(value)
19
+ render: (_args, value) => output$4(value)
18
20
  };
19
21
  const keyParameter$1 = {
20
22
  type: "string",
21
23
  required: true,
22
24
  description: "Stable key shown by the corresponding list tool."
23
25
  };
24
- const json = (value) => JSON.parse(JSON.stringify(value));
26
+ const json$1 = (value) => JSON.parse(JSON.stringify(value));
25
27
  /** Resolves every call from its authoring chat identity, then reads the files afresh. */
26
28
  var AuthoredWorldReader = class {
27
29
  worlds;
@@ -51,7 +53,7 @@ function listTool(reader, name, description, select, summarize) {
51
53
  output: jsonOutput$3,
52
54
  isConcurrencySafe: () => true,
53
55
  async execute(_args, exec) {
54
- return json(select((await reader.read(exec)).state).map(summarize));
56
+ return json$1(select((await reader.read(exec)).state).map(summarize));
55
57
  }
56
58
  });
57
59
  }
@@ -65,7 +67,7 @@ function getTool(reader, name, description, select) {
65
67
  async execute(args, exec) {
66
68
  const found = select((await reader.read(exec)).state).find((entry) => entry.key === args.key);
67
69
  if (found === void 0) throw new Error(`there is no ${name.slice(4).replaceAll("_", " ")} with key "${args.key}"`);
68
- return json(found);
70
+ return json$1(found);
69
71
  }
70
72
  });
71
73
  }
@@ -81,7 +83,7 @@ function authoredWorldReadTools(reader) {
81
83
  async execute(_args, exec) {
82
84
  const { record, state } = await reader.read(exec);
83
85
  const document = JSON.parse(await readFile(join(record.directory, "world.json"), "utf8"));
84
- return json({
86
+ return json$1({
85
87
  id: record.summary.id,
86
88
  name: record.summary.name,
87
89
  description: record.summary.description,
@@ -160,7 +162,7 @@ function authoredWorldReadTools(reader) {
160
162
  isConcurrencySafe: () => true,
161
163
  async execute(args, exec) {
162
164
  const { record } = await reader.read(exec);
163
- return json(await readAuthoredEntityDocument({
165
+ return json$1(await readAuthoredEntityDocument({
164
166
  id: record.summary.id,
165
167
  directory: record.directory
166
168
  }, args.kind, args.key));
@@ -199,7 +201,7 @@ function authoredWorldReadTools(reader) {
199
201
  const { record } = await reader.read(exec);
200
202
  const found = (await readTriggerDocuments(record.directory)).find((entry) => entry["key"] === args.key);
201
203
  if (found === void 0) throw new Error(`there is no trigger with key "${args.key}"`);
202
- return json(found);
204
+ return json$1(found);
203
205
  }
204
206
  }),
205
207
  defineTool({
@@ -228,7 +230,7 @@ function authoredWorldReadTools(reader) {
228
230
  output: jsonOutput$3,
229
231
  isConcurrencySafe: () => true,
230
232
  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)));
233
+ 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
234
  }
233
235
  })
234
236
  ];
@@ -236,13 +238,13 @@ function authoredWorldReadTools(reader) {
236
238
  //#endregion
237
239
  //#region src/host/authoring/pack-tools.ts
238
240
  const PACK_MUTATION_TOOLS = ["delete_world_pack_file"];
239
- const output$2 = (value) => [{
241
+ const output$3 = (value) => [{
240
242
  type: "text",
241
243
  text: JSON.stringify(value, null, 2)
242
244
  }];
243
245
  const jsonOutput$2 = {
244
246
  schema: { type: "json" },
245
- render: (_args, value) => output$2(value)
247
+ render: (_args, value) => output$3(value)
246
248
  };
247
249
  /** 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
250
  function relativeTo(exec, path) {
@@ -345,13 +347,13 @@ function worldPackTools(reader) {
345
347
  //#endregion
346
348
  //#region src/host/authoring/prompt-tools.ts
347
349
  const PROMPT_MUTATION_TOOLS = ["write_world_prompt", "delete_world_prompt"];
348
- const output$1 = (value) => [{
350
+ const output$2 = (value) => [{
349
351
  type: "text",
350
352
  text: JSON.stringify(value, null, 2)
351
353
  }];
352
354
  const jsonOutput$1 = {
353
355
  schema: { type: "json" },
354
- render: (_args, value) => output$1(value)
356
+ render: (_args, value) => output$2(value)
355
357
  };
356
358
  const idParameter = {
357
359
  type: "string",
@@ -439,14 +441,82 @@ function worldPromptTools(reader, shipped = shippedPromptsDirectory()) {
439
441
  ];
440
442
  }
441
443
  //#endregion
444
+ //#region src/host/authoring/approval-summary.ts
445
+ const MAX_FIELDS = 5;
446
+ function clip(value, max) {
447
+ const flat = (typeof value === "string" ? `“${value}”` : JSON.stringify(value) ?? "").replace(/\s+/g, " ");
448
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
449
+ }
450
+ const records = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
451
+ /** What a replacement changes, field by field at the top level: the person sees the edit, not just that there is one. */
452
+ function changedFields(before, after) {
453
+ if (!records(before) || !records(after)) return {
454
+ en: "",
455
+ zh: ""
456
+ };
457
+ const parts = [];
458
+ for (const key of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])) {
459
+ if (isDeepStrictEqual(before[key], after[key])) continue;
460
+ if (!(key in before)) parts.push(`+${key} ${clip(after[key], 60)}`);
461
+ else if (!(key in after)) parts.push(`-${key}`);
462
+ else parts.push(`${key} ${clip(before[key], 40)} → ${clip(after[key], 40)}`);
463
+ }
464
+ if (parts.length === 0) return {
465
+ en: "no field changes",
466
+ zh: "没有字段变化"
467
+ };
468
+ const shown = parts.slice(0, MAX_FIELDS).join("; ");
469
+ const more = parts.length - MAX_FIELDS;
470
+ return {
471
+ en: more > 0 ? `${shown}; and ${more} more` : shown,
472
+ zh: more > 0 ? `${shown};另有 ${more} 项` : shown
473
+ };
474
+ }
475
+ /** A newly made document: its name and which fields it fills. */
476
+ function createdFields(document) {
477
+ if (!records(document)) return {
478
+ en: "",
479
+ zh: ""
480
+ };
481
+ const keys = Object.keys(document);
482
+ if (keys.length === 0) return {
483
+ en: "",
484
+ zh: ""
485
+ };
486
+ const name = typeof document["name"] === "string" ? `named ${clip(document["name"], 60)}, ` : "";
487
+ const zhName = typeof document["name"] === "string" ? `名为${clip(document["name"], 60)},` : "";
488
+ const listed = keys.slice(0, 8).join(", ") + (keys.length > 8 ? ", …" : "");
489
+ return {
490
+ en: `${name}fields: ${listed}`,
491
+ zh: `${zhName}字段:${listed}`
492
+ };
493
+ }
494
+ function sizeOf(text) {
495
+ if (typeof text !== "string") return {
496
+ en: "",
497
+ zh: ""
498
+ };
499
+ return {
500
+ en: `${text.length} characters, starting ${clip(text, 70)}`,
501
+ zh: `${text.length} 个字符,开头:${clip(text, 70)}`
502
+ };
503
+ }
504
+ function plain(value, max = 220) {
505
+ const text = clip(value, max);
506
+ return {
507
+ en: text,
508
+ zh: text
509
+ };
510
+ }
511
+ //#endregion
442
512
  //#region src/host/authoring/write-tools.ts
443
- const output = (value) => [{
513
+ const output$1 = (value) => [{
444
514
  type: "text",
445
515
  text: JSON.stringify(value, null, 2)
446
516
  }];
447
517
  const jsonOutput = {
448
518
  schema: { type: "json" },
449
- render: (_args, value) => output(value)
519
+ render: (_args, value) => output$1(value)
450
520
  };
451
521
  const kindParameter = {
452
522
  type: "string",
@@ -642,11 +712,13 @@ function authoredWorldWriteTools(reader) {
642
712
  /**
643
713
  * 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
714
  * @param reviewing - whether the authoring chat is in such a turn.
715
+ * @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
716
  */
646
- async function authoringApproval(exec, next, reviewing = () => Promise.resolve(false)) {
717
+ async function authoringApproval(exec, next, reviewing = () => Promise.resolve(false), options = {}) {
647
718
  if (!AUTHORING_MUTATION_TOOLS.has(exec.name) || exec.agent === void 0 || authoredWorldOf(exec.agent.session.id) === void 0) return await next();
648
719
  const args = exec.arguments;
649
- if (exec.name === "import_preset" && exec.agent !== void 0) return {
720
+ const auto = options.auto?.() === true;
721
+ if (exec.name === "import_preset" && exec.agent !== void 0 && !auto) return {
650
722
  kind: "ask",
651
723
  reason: "replace the authored world's narration and character-style prompts with ones made from the uploaded preset",
652
724
  displayReason: {
@@ -665,7 +737,7 @@ async function authoringApproval(exec, next, reviewing = () => Promise.resolve(f
665
737
  kind: "deny",
666
738
  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
739
  };
668
- if (importing) return await next();
740
+ if (importing || auto) return await next();
669
741
  if (pack) {
670
742
  const target = `file “${String(args["path"])}” of interface pack “${String(args["pack"])}”`;
671
743
  const remove = exec.name.startsWith("delete");
@@ -684,25 +756,399 @@ async function authoringApproval(exec, next, reviewing = () => Promise.resolve(f
684
756
  return {
685
757
  kind: "ask",
686
758
  reason: `${remove ? "delete" : "write"} authored world ${target}`,
687
- displayReason: {
688
- en: `${remove ? "Delete" : "Write"} ${target} in the world files?`,
689
- zh: `${remove ? "删除" : "写入"}世界文件中的${target}?`
690
- }
759
+ displayReason: withDetail({
760
+ en: `${remove ? "Delete" : "Write"} ${target} in the world files`,
761
+ zh: `${remove ? "删除" : "写入"}世界文件中的${target}`
762
+ }, remove ? void 0 : sizeOf(args["text"]))
691
763
  };
692
764
  }
693
765
  const kind = typeof args["kind"] === "string" ? args["kind"] : exec.name === "edit_world_relationship" ? "relationship" : exec.name.endsWith("trigger") ? "trigger" : "plots";
694
766
  const key = typeof args["key"] === "string" ? args["key"] : "";
695
767
  const target = key === "" ? kind : `${kind} “${key}”`;
696
768
  const action = exec.name.startsWith("create") ? "Create" : exec.name.startsWith("delete") ? "Delete" : exec.name === "write_world_trigger" ? "Write" : "Edit";
769
+ const detail = await detailOf(exec, kind, key, options.current).catch(() => void 0);
697
770
  return {
698
771
  kind: "ask",
699
772
  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}?`
773
+ displayReason: withDetail({
774
+ en: `${action} ${target} in the world files`,
775
+ zh: `${action === "Create" ? "创建" : action === "Delete" ? "删除" : action === "Write" ? "写入" : "编辑"}世界文件中的${target}`
776
+ }, detail)
777
+ };
778
+ }
779
+ function withDetail(headline, detail) {
780
+ return detail === void 0 || detail.en === "" ? {
781
+ en: `${headline.en}?`,
782
+ zh: `${headline.zh}?`
783
+ } : {
784
+ en: `${headline.en}: ${detail.en}`,
785
+ zh: `${headline.zh}:${detail.zh}`
786
+ };
787
+ }
788
+ /** What the change is, in a line the approval shows: the question is only useful if it says what is being decided. */
789
+ async function detailOf(exec, kind, key, current) {
790
+ const args = exec.arguments;
791
+ switch (exec.name) {
792
+ case "create_world_element": return createdFields(args["document"]);
793
+ case "replace_world_element": {
794
+ const before = exec.agent === void 0 ? void 0 : await current?.(exec.agent.session.id, kind, key);
795
+ return before === void 0 ? createdFields(args["document"]) : changedFields(before, args["document"]);
703
796
  }
797
+ case "edit_world_relationship": return plain(args["change"]);
798
+ case "replace_world_plots": return Array.isArray(args["plots"]) ? {
799
+ en: `${args["plots"].length} plots`,
800
+ zh: `${args["plots"].length} 条剧情`
801
+ } : void 0;
802
+ case "write_world_trigger": return createdFields(args["document"]);
803
+ default: return;
804
+ }
805
+ }
806
+ //#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;
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
704
874
  };
705
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
+ }));
947
+ }
948
+ const output = {
949
+ schema: { type: "json" },
950
+ render: (_args, value) => [{
951
+ type: "text",
952
+ text: JSON.stringify(value, null, 1)
953
+ }]
954
+ };
955
+ 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
+ /**
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.
965
+ */
966
+ function cardTools(worlds, options = {}) {
967
+ const withRecords = options.records !== false;
968
+ const source = async (exec) => {
969
+ const id = idOf(exec);
970
+ const record = await worlds.find(id);
971
+ 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;
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
999
+ },
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
1020
+ },
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({
1080
+ piece: piece.id,
1081
+ 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
+ ];
1129
+ }
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
+ }];
1150
+ });
1151
+ }
706
1152
  //#endregion
707
1153
  //#region src/authoring.ts
708
1154
  const name = "@dsh-agentic-roleplay/core/authoring";
@@ -731,6 +1177,7 @@ function apply(ctx) {
731
1177
  for (const tool of worldPromptTools(reader)) ctx.tools.register(tool);
732
1178
  for (const tool of worldPackTools(reader)) ctx.tools.register(tool);
733
1179
  for (const tool of importTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
1180
+ for (const tool of cardTools(ctx.roleplayWorlds)) ctx.tools.register(tool);
734
1181
  for (const tool of presetTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
735
1182
  for (const tool of translateTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
736
1183
  importHooks(ctx, ctx.roleplayWorlds, prompting);
@@ -752,7 +1199,18 @@ function apply(ctx) {
752
1199
  const world = authoredWorldOf(chat);
753
1200
  return world === void 0 ? void 0 : ctx.roleplayAuthoringLanguages.get(world);
754
1201
  }, () => ctx.roleplayImport.settings.reasoning);
755
- ctx.on("tools/pre-execute", (exec, next) => authoringApproval(exec, next, reviewing));
1202
+ const current = async (chat, kind, key) => {
1203
+ const id = authoredWorldOf(chat);
1204
+ const record = id === void 0 ? void 0 : await ctx.roleplayWorlds.find(id);
1205
+ return record === void 0 ? void 0 : await readAuthoredEntityDocument({
1206
+ id: record.summary.id,
1207
+ directory: record.directory
1208
+ }, kind, key);
1209
+ };
1210
+ ctx.on("tools/pre-execute", (exec, next) => authoringApproval(exec, next, reviewing, {
1211
+ auto: () => ctx.roleplayImport.settings.approval === "auto",
1212
+ current
1213
+ }));
756
1214
  for (const [name, order, id] of [[
757
1215
  "WORLD_AUTHORING_PERSONA",
758
1216
  ctx.systemPrompt.getSectionOrder("DEPLOYMENT_PERSONA_PREFIX"),