@dsh-agentic-roleplay/core 0.2.1 → 0.3.0

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.
@@ -12,6 +12,14 @@ function roleplaySessionOf(chat) {
12
12
  return UUID_V4.test(id) ? id : void 0;
13
13
  }
14
14
  //#endregion
15
- export { roleplaySessionOf as n, chatSessionId as t };
15
+ //#region src/host/prompts/access.ts
16
+ /** The prompt `id` in `language`, from the library of the agent's own context. */
17
+ function promptFor(agent, id, language, variables) {
18
+ const library = agent.ctx.get("roleplayPrompts");
19
+ if (library === void 0) throw new Error("the prompt library is not running");
20
+ return library.text(id, language, variables, roleplaySessionOf(agent.session.id));
21
+ }
22
+ //#endregion
23
+ export { chatSessionId as n, roleplaySessionOf as r, promptFor as t };
16
24
 
17
- //# sourceMappingURL=chat-AKrVcWIC.js.map
25
+ //# sourceMappingURL=access-EbNdZFbk.js.map
package/lib/authoring.js CHANGED
@@ -1,11 +1,117 @@
1
- import { C as endReview, E as isReviewing, J as listWorldPrompts, K as PROSE_PROMPTS, O as survey, S as build, T as importPhase, X as writeWorldPrompt, Y as readWorldPrompt, _t as parseImportCommand, a as replaceAuthoredEntity, b as authoredWorldOf, d as editWorldPlots, f as editWorldRelation, g as readWorldEditor, i as readAuthoredEntityDocument, lt as InvalidEditProblems, mt as parseRelationEdit, n as createAuthoredEntity, nt as IMPORT_FOLDER, q as deleteWorldPrompt, r as deleteAuthoredEntity, t as AUTHORED_ENTITY_KINDS, w as finish } from "./documents-Bu5uYRZB.js";
2
- import { P as shippedPromptsDirectory, T as formatIssue, a as packIds, b as parsePlotsFile, d as packPath, f as readPack, g as SURFACE_NAMES, h as PACK_MEDIA_TYPES, l as isPackId, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-ByP1J-zj.js";
1
+ import { $ as writeWorldPrompt, A as survey, D as importPhase, E as finish, O as isReviewing, Q as readWorldPrompt, S as authoredWorldOf, T as endReview, U as TRIGGERS_FILE_NAME, X as deleteWorldPrompt, Y as PROSE_PROMPTS, Z as listWorldPrompts, _t as parseRelationEdit, a as replaceAuthoredEntity, at as IMPORT_FOLDER, b as triggerProblemsOf, bt as parseImportCommand, d as editWorldPlots, f as editWorldRelation, ft as InvalidEditProblems, g as readWorldEditor, i as readAuthoredEntityDocument, n as createAuthoredEntity, r as deleteAuthoredEntity, t as AUTHORED_ENTITY_KINDS, w as build, x as loadWorldParts } from "./documents-7GMc5NnW.js";
2
+ import { P as shippedPromptsDirectory, T as formatIssue, a as packIds, b as parsePlotsFile, d as packPath, f as readPack, g as SURFACE_NAMES, h as PACK_MEDIA_TYPES, l as isPackId, m as PACK_LIMITS, p as PACK_ACTIONS } from "./packs-alJTiDM2.js";
3
3
  import { A as runChild } from "./generator-HPifO3Kk.js";
4
- import { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
5
  import { existsSync, lstatSync } from "node:fs";
6
+ import { randomUUID } from "node:crypto";
6
7
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
7
8
  import { defineTool } from "@deepseek-ai/dsh-tools";
8
- import { mkdir, readFile, rename } from "node:fs/promises";
9
+ import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
10
+ import { readTriggerDefinition } from "@dsh-agentic-roleplay/state";
11
+ //#region src/host/triggers/files.ts
12
+ /** The fields of a trigger in the file; any other is a mistake that would otherwise be dropped without a word. */
13
+ const FIELDS = /* @__PURE__ */ new Set([
14
+ "key",
15
+ "name",
16
+ "when",
17
+ "effects",
18
+ "repeat",
19
+ "cooldown_seconds",
20
+ "chance",
21
+ "priority",
22
+ "expires",
23
+ "announce"
24
+ ]);
25
+ const isDocument = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
26
+ /** The documents of `<world>/triggers.json` as written; none when the file is not there. @throws {InvalidEditProblems} when it is not a list of objects. */
27
+ async function readTriggerDocuments(directory) {
28
+ let text;
29
+ try {
30
+ text = await readFile(join(directory, TRIGGERS_FILE_NAME), "utf8");
31
+ } catch (error) {
32
+ if (error.code === "ENOENT") return [];
33
+ throw error;
34
+ }
35
+ let data;
36
+ try {
37
+ data = JSON.parse(text.replace(/^/, ""));
38
+ } catch (error) {
39
+ throw new InvalidEditProblems([`triggers.json is not valid JSON: ${error instanceof Error ? error.message : String(error)}`]);
40
+ }
41
+ if (!Array.isArray(data) || !data.every(isDocument)) throw new InvalidEditProblems(["triggers.json is not a list of triggers"]);
42
+ return data;
43
+ }
44
+ async function writeDocuments(directory, documents) {
45
+ const file = join(directory, TRIGGERS_FILE_NAME);
46
+ const temporary = join(dirname(file), `.${basename(file)}.${process.pid}.${randomUUID()}.tmp`);
47
+ try {
48
+ const mode = await stat(file).then((value) => value.mode, () => void 0);
49
+ await writeFile(temporary, `${JSON.stringify(documents, null, 2)}\n`, mode === void 0 ? {} : { mode });
50
+ await rename(temporary, file);
51
+ } catch (error) {
52
+ await rm(temporary, { force: true });
53
+ throw error;
54
+ }
55
+ }
56
+ /** The keys of the triggers a condition waits for. */
57
+ function waitsFor(condition) {
58
+ switch (condition.type) {
59
+ case "fired": return [condition.trigger];
60
+ case "all":
61
+ case "any": return condition.conditions.flatMap(waitsFor);
62
+ case "not": return waitsFor(condition.condition);
63
+ default: return [];
64
+ }
65
+ }
66
+ /**
67
+ * Makes or replaces one trigger of the world, by key, from a complete document in the file format. It is read as a session start reads it, and
68
+ * what it names that the world does not have is refused, with every problem; nothing is written then.
69
+ * @throws {InvalidEditProblems}
70
+ */
71
+ async function writeTriggerDocument(directory, parts, key, document) {
72
+ if (!isDocument(document)) throw new InvalidEditProblems(["document must be a JSON object"]);
73
+ const unknown = Object.keys(document).filter((field) => !FIELDS.has(field));
74
+ if (unknown.length > 0) throw new InvalidEditProblems(unknown.map((field) => `"${field}" is not a field of a trigger (${[...FIELDS].join(", ")})`));
75
+ const written = {
76
+ ...document,
77
+ key
78
+ };
79
+ const parsed = readTriggerDefinition(written, "trigger");
80
+ if ("problems" in parsed) throw new InvalidEditProblems(parsed.problems);
81
+ const documents = await readTriggerDocuments(directory);
82
+ const at = documents.findIndex((entry) => entry["key"] === key);
83
+ const others = documents.filter((_, index) => index !== at).flatMap((entry) => {
84
+ const read = readTriggerDefinition(entry, "trigger");
85
+ return "definition" in read ? [read.definition] : [];
86
+ });
87
+ const problems = triggerProblemsOf(parts, [...others, parsed.definition]).get(key) ?? [];
88
+ if (problems.length > 0) throw new InvalidEditProblems(problems);
89
+ await writeDocuments(directory, at < 0 ? [...documents, written] : documents.map((entry, index) => index === at ? written : entry));
90
+ return at < 0 ? "created" : "replaced";
91
+ }
92
+ /**
93
+ * Removes one trigger from the world's file, keeping its document in `.trash/triggers` so that it can be put back. A trigger that others wait for
94
+ * cannot be removed.
95
+ * @returns where the document was kept.
96
+ * @throws {InvalidEditProblems}
97
+ */
98
+ async function deleteTriggerDocument(directory, key) {
99
+ const documents = await readTriggerDocuments(directory);
100
+ const found = documents.find((entry) => entry["key"] === key);
101
+ if (found === void 0) throw new InvalidEditProblems([`there is no trigger "${key}"`]);
102
+ const waiting = documents.flatMap((entry) => {
103
+ const read = readTriggerDefinition(entry, "trigger");
104
+ return "definition" in read && read.definition.key !== key && waitsFor(read.definition.condition).includes(key) ? [read.definition.key] : [];
105
+ });
106
+ if (waiting.length > 0) throw new InvalidEditProblems([`${waiting.join(", ")} wait${waiting.length === 1 ? "s" : ""} for "${key}" to fire; change ${waiting.length === 1 ? "it" : "them"} first`]);
107
+ const trash = join(directory, ".trash", "triggers");
108
+ await mkdir(trash, { recursive: true });
109
+ const kept = join(trash, `${key}-${Date.now()}-${randomUUID()}.json`);
110
+ await writeFile(kept, `${JSON.stringify(found, null, 2)}\n`, { flag: "wx" });
111
+ await writeDocuments(directory, documents.filter((entry) => entry !== found));
112
+ return kept;
113
+ }
114
+ //#endregion
9
115
  //#region src/host/authoring/read-tools.ts
10
116
  const output$4 = (value) => [{
11
117
  type: "text",
@@ -175,6 +281,32 @@ function authoredWorldReadTools(reader) {
175
281
  key: entry.definition.id,
176
282
  name: entry.definition.name
177
283
  }))),
284
+ listTool(reader, "list_world_triggers", "List the world’s triggers (what the world does by itself): key, name, what each waits for (when), the kinds of its effects, whether it repeats, and what it names that the world does not have (problems).", (world) => (world.triggers ?? []).map((entry) => ({
285
+ ...entry,
286
+ name: entry.name
287
+ })), (entry) => ({
288
+ key: entry.key,
289
+ name: entry.name,
290
+ when: entry.when,
291
+ effects: entry.effects.map((effect) => effect.type),
292
+ repeat: entry.repeat,
293
+ priority: entry.priority,
294
+ announced: entry.announced,
295
+ problems: entry.problems
296
+ })),
297
+ defineTool({
298
+ name: "get_world_trigger",
299
+ description: "Read the exact snake_case JSON document stored for one trigger in triggers.json. Use this before replacing a trigger.",
300
+ parameters: { key: keyParameter$1 },
301
+ output: jsonOutput$3,
302
+ isConcurrencySafe: () => true,
303
+ async execute(args, exec) {
304
+ const { record } = await reader.read(exec);
305
+ const found = (await readTriggerDocuments(record.directory)).find((entry) => entry["key"] === args.key);
306
+ if (found === void 0) throw new Error(`there is no trigger with key "${args.key}"`);
307
+ return json$1(found);
308
+ }
309
+ }),
178
310
  defineTool({
179
311
  name: "list_relationships",
180
312
  description: "Read authored character relationships, knowledge, faction memberships, social ties and map exits. Optionally narrow by kind or endpoint key.",
@@ -490,6 +622,8 @@ const AUTHORING_MUTATION_TOOLS = /* @__PURE__ */ new Set([
490
622
  "delete_world_element",
491
623
  "edit_world_relationship",
492
624
  "replace_world_plots",
625
+ "write_world_trigger",
626
+ "delete_world_trigger",
493
627
  ...PROMPT_MUTATION_TOOLS,
494
628
  ...PACK_MUTATION_TOOLS
495
629
  ]);
@@ -622,6 +756,43 @@ function authoredWorldWriteTools(reader) {
622
756
  };
623
757
  return result("replaced", "plots", "*", await editWorldPlots(world, { plots: args.plots.map(plotDocument) }));
624
758
  }
759
+ }),
760
+ defineTool({
761
+ name: "write_world_trigger",
762
+ description: "Create or replace one trigger (something the world does by itself) in triggers.json, from a complete document in the file format, by its key. It is read as a story start reads it and refused, with every problem, when it is malformed or names a character, place, item, variable or trigger the world does not have; read get_world_trigger first when replacing. Requires user approval.",
763
+ parameters: {
764
+ key: keyParameter,
765
+ document: {
766
+ type: "json",
767
+ required: true,
768
+ description: "Complete snake_case trigger: name, when (condition), effects (one to six: edit, beat, cue), and optionally repeat, cooldown_seconds, chance, priority, expires, announce. A beat or cue may have a while condition and names such as {where:character}."
769
+ }
770
+ },
771
+ output: jsonOutput,
772
+ async execute(args, exec) {
773
+ const { record } = await reader.read(exec);
774
+ return result(await writeTriggerDocument(record.directory, await loadWorldParts(record.directory), args.key, args.document), "trigger", args.key, await readWorldEditor({
775
+ id: record.summary.id,
776
+ directory: record.directory
777
+ }));
778
+ }
779
+ }),
780
+ defineTool({
781
+ name: "delete_world_trigger",
782
+ description: "Remove one trigger from triggers.json. Its document is kept in the world’s .trash/triggers so it can be put back. A trigger that others wait for cannot be removed. Requires user approval.",
783
+ parameters: { key: keyParameter },
784
+ output: jsonOutput,
785
+ async execute(args, exec) {
786
+ const { record } = await reader.read(exec);
787
+ const kept = await deleteTriggerDocument(record.directory, args.key);
788
+ return result("deleted", "trigger", args.key, await readWorldEditor({
789
+ id: record.summary.id,
790
+ directory: record.directory
791
+ }), {
792
+ recoverable: true,
793
+ trashPath: kept
794
+ });
795
+ }
625
796
  })
626
797
  ];
627
798
  }
@@ -668,16 +839,16 @@ async function authoringApproval(exec, next, reviewing = () => Promise.resolve(f
668
839
  }
669
840
  };
670
841
  }
671
- const kind = typeof args["kind"] === "string" ? args["kind"] : exec.name === "edit_world_relationship" ? "relationship" : "plots";
842
+ const kind = typeof args["kind"] === "string" ? args["kind"] : exec.name === "edit_world_relationship" ? "relationship" : exec.name.endsWith("trigger") ? "trigger" : "plots";
672
843
  const key = typeof args["key"] === "string" ? args["key"] : "";
673
844
  const target = key === "" ? kind : `${kind} “${key}”`;
674
- const action = exec.name.startsWith("create") ? "Create" : exec.name.startsWith("delete") ? "Delete" : "Edit";
845
+ const action = exec.name.startsWith("create") ? "Create" : exec.name.startsWith("delete") ? "Delete" : exec.name === "write_world_trigger" ? "Write" : "Edit";
675
846
  return {
676
847
  kind: "ask",
677
848
  reason: `${action.toLowerCase()} authored world ${target}`,
678
849
  displayReason: {
679
850
  en: `${action} ${target} in the world files?`,
680
- zh: `${action === "Create" ? "创建" : action === "Delete" ? "删除" : "编辑"}世界文件中的${target}?`
851
+ zh: `${action === "Create" ? "创建" : action === "Delete" ? "删除" : action === "Write" ? "写入" : "编辑"}世界文件中的${target}?`
681
852
  }
682
853
  };
683
854
  }