@dsh-agentic-roleplay/core 0.1.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.
Files changed (52) hide show
  1. package/README.md +1 -1
  2. package/lib/{chat-AKrVcWIC.js → access-EbNdZFbk.js} +10 -2
  3. package/lib/authoring.js +469 -17
  4. package/lib/client.js +3013 -607
  5. package/lib/client.js.map +1 -1
  6. package/lib/compaction.js +2 -3
  7. package/lib/{activity-BbqFG9-3.js → deliver--uMhC6oO.js} +741 -55
  8. package/lib/{documents-ZVoUTnD2.js → documents-7GMc5NnW.js} +108 -5
  9. package/lib/{gallery-KGCdeCnM.js → gallery-DUeBMHQX.js} +2 -2
  10. package/lib/{generator-NYnNdpWb.js → generator-HPifO3Kk.js} +125 -20
  11. package/lib/images.js +3 -3
  12. package/lib/index.js +865 -15
  13. package/lib/{narration-DcnCqA1l.js → narration-CKZTk5UE.js} +19 -4
  14. package/lib/orchestration.js +373 -207
  15. package/lib/packs-alJTiDM2.js +1336 -0
  16. package/lib/{presenter-agent-7j1c7QEz.js → presenter-agent-PX1WVaJB.js} +4 -4
  17. package/package.json +5 -3
  18. package/packs/scene/map.html +12 -0
  19. package/packs/scene/map.js +55 -0
  20. package/packs/scene/pack.json +11 -0
  21. package/packs/scene/strip.html +11 -0
  22. package/packs/scene/strip.js +26 -0
  23. package/packs/scene/style.css +16 -0
  24. package/prompts/en/roleplay/ask-answerer.md +3 -0
  25. package/prompts/en/roleplay/ask-question.md +2 -0
  26. package/prompts/en/roleplay/character-decide.md +1 -1
  27. package/prompts/en/roleplay/character-lookup.md +1 -1
  28. package/prompts/en/roleplay/game-master.md +5 -1
  29. package/prompts/en/roleplay/ooc-empty.md +1 -1
  30. package/prompts/en/roleplay/reflection.md +9 -0
  31. package/prompts/en/world/procedure.md +1 -1
  32. package/prompts/en/world/welcome.md +1 -1
  33. package/prompts/zh/roleplay/ask-answerer.md +3 -0
  34. package/prompts/zh/roleplay/ask-question.md +2 -0
  35. package/prompts/zh/roleplay/character-decide.md +1 -1
  36. package/prompts/zh/roleplay/character-lookup.md +1 -1
  37. package/prompts/zh/roleplay/game-master.md +5 -1
  38. package/prompts/zh/roleplay/ooc-empty.md +1 -1
  39. package/prompts/zh/roleplay/reflection.md +9 -0
  40. package/prompts/zh/world/procedure.md +1 -1
  41. package/prompts/zh/world/welcome.md +1 -1
  42. package/starter-worlds/blackwater-observatory/ui/notebook/map.html +12 -0
  43. package/starter-worlds/blackwater-observatory/ui/notebook/map.js +40 -0
  44. package/starter-worlds/blackwater-observatory/ui/notebook/notebook.html +29 -0
  45. package/starter-worlds/blackwater-observatory/ui/notebook/notebook.js +45 -0
  46. package/starter-worlds/blackwater-observatory/ui/notebook/pack.json +31 -0
  47. package/starter-worlds/blackwater-observatory/ui/notebook/skin.css +16 -0
  48. package/starter-worlds/blackwater-observatory/ui/notebook/strip.html +11 -0
  49. package/starter-worlds/blackwater-observatory/ui/notebook/strip.js +12 -0
  50. package/starter-worlds/blackwater-observatory/ui/notebook/style.css +23 -0
  51. package/lib/access-C1nFQiyT.js +0 -12
  52. package/lib/worlds-DYgjdH8O.js +0 -504
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  The UI, orchestration, world authoring, media, and filesystem integration plugin behind DSH Agentic Roleplay.
4
4
 
5
- It provides the game-master loop, autonomous character agents, world and session interfaces, authoring agents and tools, story compaction, speech integration, and image-generation workflows. Session data is provided by [`@dsh-agentic-roleplay/state`](https://www.npmjs.com/package/@dsh-agentic-roleplay/state).
5
+ It provides the bounded game-master loop, point-of-view character agents, world and session interfaces, approval-gated authoring agents and tools, story compaction, speech integration, and image-generation workflows. It turns the structured state supplied by [`@dsh-agentic-roleplay/state`](https://www.npmjs.com/package/@dsh-agentic-roleplay/state) into a playable and editable experience.
6
6
 
7
7
  ## Install
8
8
 
@@ -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,18 +1,125 @@
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-ZVoUTnD2.js";
2
- import { i as parsePlotsFile, l as formatIssue, v as shippedPromptsDirectory } from "./worlds-DYgjdH8O.js";
3
- import { A as runChild } from "./generator-NYnNdpWb.js";
4
- import { join } from "node:path";
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
+ import { A as runChild } from "./generator-HPifO3Kk.js";
4
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
+ import { existsSync, lstatSync } from "node:fs";
6
+ import { randomUUID } from "node:crypto";
5
7
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
6
8
  import { defineTool } from "@deepseek-ai/dsh-tools";
7
- import { readFile } 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
8
115
  //#region src/host/authoring/read-tools.ts
9
- const output$3 = (value) => [{
116
+ const output$4 = (value) => [{
10
117
  type: "text",
11
118
  text: JSON.stringify(value, null, 2)
12
119
  }];
13
- const jsonOutput$2 = {
120
+ const jsonOutput$3 = {
14
121
  schema: { type: "json" },
15
- render: (_args, value) => output$3(value)
122
+ render: (_args, value) => output$4(value)
16
123
  };
17
124
  const keyParameter$1 = {
18
125
  type: "string",
@@ -46,7 +153,7 @@ function listTool(reader, name, description, select, summarize) {
46
153
  name,
47
154
  description,
48
155
  parameters: {},
49
- output: jsonOutput$2,
156
+ output: jsonOutput$3,
50
157
  isConcurrencySafe: () => true,
51
158
  async execute(_args, exec) {
52
159
  return json$1(select((await reader.read(exec)).state).map(summarize));
@@ -58,7 +165,7 @@ function getTool(reader, name, description, select) {
58
165
  name,
59
166
  description,
60
167
  parameters: { key: keyParameter$1 },
61
- output: jsonOutput$2,
168
+ output: jsonOutput$3,
62
169
  isConcurrencySafe: () => true,
63
170
  async execute(args, exec) {
64
171
  const found = select((await reader.read(exec)).state).find((entry) => entry.key === args.key);
@@ -74,7 +181,7 @@ function authoredWorldReadTools(reader) {
74
181
  name: "get_world_overview",
75
182
  description: "Read the authored world’s top-level identity, description, rules, opening, tags, author and element counts.",
76
183
  parameters: {},
77
- output: jsonOutput$2,
184
+ output: jsonOutput$3,
78
185
  isConcurrencySafe: () => true,
79
186
  async execute(_args, exec) {
80
187
  const { record, state } = await reader.read(exec);
@@ -154,7 +261,7 @@ function authoredWorldReadTools(reader) {
154
261
  },
155
262
  key: keyParameter$1
156
263
  },
157
- output: jsonOutput$2,
264
+ output: jsonOutput$3,
158
265
  isConcurrencySafe: () => true,
159
266
  async execute(args, exec) {
160
267
  const { record } = await reader.read(exec);
@@ -174,6 +281,32 @@ function authoredWorldReadTools(reader) {
174
281
  key: entry.definition.id,
175
282
  name: entry.definition.name
176
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
+ }),
177
310
  defineTool({
178
311
  name: "list_relationships",
179
312
  description: "Read authored character relationships, knowledge, faction memberships, social ties and map exits. Optionally narrow by kind or endpoint key.",
@@ -197,7 +330,7 @@ function authoredWorldReadTools(reader) {
197
330
  description: "Only edges whose target has this stable key."
198
331
  }
199
332
  },
200
- output: jsonOutput$2,
333
+ output: jsonOutput$3,
201
334
  isConcurrencySafe: () => true,
202
335
  async execute(args, exec) {
203
336
  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)));
@@ -206,6 +339,168 @@ function authoredWorldReadTools(reader) {
206
339
  ];
207
340
  }
208
341
  //#endregion
342
+ //#region src/host/interface/world-packs.ts
343
+ /** The kinds of file an assistant may write, as text. */
344
+ const TEXT_EXTENSIONS = [
345
+ "html",
346
+ "css",
347
+ "js",
348
+ "json",
349
+ "txt",
350
+ "svg"
351
+ ];
352
+ const folderOf = (directory, pack) => join(directory, "ui", pack);
353
+ function checked(directory, pack) {
354
+ if (!isPackId(pack)) throw new Error(`"${pack}" is not a usable pack name (letters, digits, "-" and "_")`);
355
+ return folderOf(directory, pack);
356
+ }
357
+ /** What every pack the world carries holds and what is wrong with it. */
358
+ function listWorldPacks(directory) {
359
+ return packIds(directory).map((id) => {
360
+ const { pack, problems } = readPack(folderOf(directory, id), id, (file) => file);
361
+ const files = pack === void 0 ? [] : [...pack.files.keys()];
362
+ return {
363
+ id,
364
+ name: pack?.manifest.name ?? id,
365
+ problems,
366
+ files
367
+ };
368
+ });
369
+ }
370
+ /** What is wrong with a pack (nothing when it can be used). */
371
+ function checkWorldPack(directory, pack) {
372
+ const folder = checked(directory, pack);
373
+ if (!existsSync(folder)) throw new Error(`the world carries no pack "${pack}"`);
374
+ return readPack(folder, pack, (file) => file).problems;
375
+ }
376
+ /** Moves a file of a pack into the world's `.trash`. @returns where it went, and what is wrong with the pack now. */
377
+ async function deleteWorldPackFile(directory, pack, path) {
378
+ const relative = packPath(path);
379
+ if (relative === void 0 || !(extname(relative).slice(1).toLowerCase() in PACK_MEDIA_TYPES)) throw new Error(`"${path}" is not a file of a pack`);
380
+ const folder = checked(directory, pack);
381
+ const file = join(folder, ...relative.split("/"));
382
+ if (!existsSync(file)) throw new Error(`the pack "${pack}" has no file "${path}"`);
383
+ const aside = join(directory, ".trash", "ui", pack, `${relative.replaceAll("/", "__")}.${Date.now()}`);
384
+ await mkdir(dirname(aside), { recursive: true });
385
+ await rename(file, aside);
386
+ return {
387
+ trashPath: aside,
388
+ problems: existsSync(join(folder, "pack.json")) ? readPack(folder, pack, (address) => address).problems : [{
389
+ file: "pack.json",
390
+ message: "the pack has no pack.json"
391
+ }]
392
+ };
393
+ }
394
+ //#endregion
395
+ //#region src/host/authoring/pack-tools.ts
396
+ const PACK_MUTATION_TOOLS = ["delete_world_pack_file"];
397
+ const output$3 = (value) => [{
398
+ type: "text",
399
+ text: JSON.stringify(value, null, 2)
400
+ }];
401
+ const jsonOutput$2 = {
402
+ schema: { type: "json" },
403
+ render: (_args, value) => output$3(value)
404
+ };
405
+ /** 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. */
406
+ function relativeTo(exec, path) {
407
+ const cwd = exec.agent?.session.header.cwd;
408
+ return cwd === void 0 ? path : relative(cwd, path);
409
+ }
410
+ const packParameter = {
411
+ type: "string",
412
+ required: true,
413
+ description: "The pack name (its folder under ui/), such as atlas."
414
+ };
415
+ const pathParameter = {
416
+ type: "string",
417
+ required: true,
418
+ description: "A path inside the pack with \"/\", such as pack.json or img/map.svg."
419
+ };
420
+ /** What an assistant needs to write a pack; the same facts the author docs give a person. */
421
+ const PACK_GUIDE = `Write and read the files of a pack with the file tools write, edit and read, at the path <world folder>/ui/<pack>/<file>. Use the short relative path given with this guide (such as my-world/ui/atlas/pack.json), not the long absolute one, which is easy to mistype; in this chat they reach nothing else, only text files, and every change asks the person first. Delete a file with delete_world_pack_file.
422
+
423
+ An interface pack changes how a story looks and adds small pieces of interface. It is a folder ui/<pack>/ of the world with a pack.json and the files it names. Sessions started from the world copy it; a pack with problems stops the session from starting, so check it with check_world_pack after writing.
424
+
425
+ pack.json (api 1): { "name", "version", "description", "api": 1, "theme": { "--dsw-alias-<token>": { "light": "#...", "dark": "#..." } }, "skin": "skin.css", "actions": [${PACK_ACTIONS.map((action) => `"${action}"`).join(", ")}], "surfaces": { "hud": { "file": "hud.html", "height": 48 }, "tab": { "file": "map.html", "title": "Map" } } }. Surfaces: ${SURFACE_NAMES.join(", ")} (hud is a strip above the input box and its controls, dock a strip just above the input box for buttons, opening a card shown only until the first turn is played, backdrop a layer behind the story's text that takes no clicks, tab a page beside Chat, sidebar a page of any size in the right sidebar with a Back button above it; the strips hud, dock and opening ask for their height with rp.resize). actions lists what the pages may do for the player: say (send words as the player), fill (put words in the input box), choose (take a suggested action as the input), open (show the pack's tab or sidebar page); leave out what is not needed.
426
+
427
+ skin.css restyles the story's own elements and nothing else: every part of every selector must name one with [data-rp="..."], and url() may point only to files of the pack. Elements: narration (a turn), prose (a narration paragraph), utterance (a spoken line) with avatar, speaker and words inside, ooc, suggestions and suggestion, turns, and the frames hud, dock, opening and backdrop. Only style rules, @media, @supports, @keyframes and @font-face are allowed; no @import, nesting or escapes outside strings.
428
+
429
+ A surface is an HTML file with its own css and js files beside it (relative addresses). It runs in a sandbox: no cookies, storage or access to the page, and no network except fetching the pack's own files; workers, WebAssembly, canvas and WebGL work. The page gives it an rp object: rp.state() (a promise of the player view: use await or .then) and rp.watch(fn) (calls fn(view) at once and after every change; the usual way to draw a surface). The view is story {name, turn}, player {key, name, summary, publicState}, place {key, name, description, features, exits [{name, open}], items [{name, quantity}], here [{key, name, publicState}]}, time {iso, zone, text}, carried [{name, quantity, where}], variables [{subject, name, value}], map {places [{key, name, parent?, here}], routes [{from, to}]}, suggestions []), rp.on('turn' | 'suggestions' | 'theme', fn), rp.say(text), rp.fill(text), rp.choose(index), rp.open('tab' | 'sidebar'), rp.history(n) (the last turns as the story stands: {turn, player, segments [{type, name?, text}], note?}), rp.storage.get/set/remove (JSON, 64 KB), rp.resize(height) (24 to 320; the opening card 120 to 640), rp.theme(). The frame has the DSH colours as CSS variables such as var(--dsw-alias-label-primary), var(--dsw-alias-bg-layer-1), var(--dsw-alias-border-l3), var(--dsw-alias-brand-primary); use them so the page fits light and dark.
430
+
431
+ Limits: ${PACK_LIMITS.files} files, ${PACK_LIMITS.bytes / 1024 / 1024} MB, ${PACK_LIMITS.fileBytes / 1024} KB per file, ${PACK_LIMITS.depth} folders deep; names use letters, digits, "-", "_" and "."; only text files (html, css, js, json, txt, svg) can be written; pictures and fonts are added by hand.`;
432
+ /**
433
+ * Read, write and check the interface packs a world carries. The files are the ones session start copies,
434
+ * so they are checked as it checks them.
435
+ */
436
+ function worldPackTools(reader) {
437
+ return [
438
+ defineTool({
439
+ name: "world_pack_guide",
440
+ description: "How to write an interface pack: where its files go (the folder is returned with the guide), the manifest, the skin, the surfaces, the rp object a surface gets, what it is told, and the limits. Read it before writing a pack.",
441
+ parameters: {},
442
+ output: jsonOutput$2,
443
+ isConcurrencySafe: () => true,
444
+ async execute(_args, exec) {
445
+ const { record } = await reader.read(exec);
446
+ return {
447
+ folder: join(record.directory, "ui"),
448
+ relative: relativeTo(exec, join(record.directory, "ui")),
449
+ guide: PACK_GUIDE
450
+ };
451
+ }
452
+ }),
453
+ defineTool({
454
+ name: "list_world_packs",
455
+ description: "List the interface packs the world carries, their files and what is wrong with each. Each pack has a path: the folder its files go in, as the file tools take it.",
456
+ parameters: {},
457
+ output: jsonOutput$2,
458
+ isConcurrencySafe: () => true,
459
+ async execute(_args, exec) {
460
+ const { record } = await reader.read(exec);
461
+ return listWorldPacks(record.directory).map((entry) => ({
462
+ ...entry,
463
+ path: relativeTo(exec, join(record.directory, "ui", entry.id))
464
+ }));
465
+ }
466
+ }),
467
+ defineTool({
468
+ name: "check_world_pack",
469
+ description: "Check a pack of this world as session start will: the manifest, the theme, the skin, the surfaces and every file. An empty list of problems means it can be used.",
470
+ parameters: { pack: packParameter },
471
+ output: jsonOutput$2,
472
+ isConcurrencySafe: () => true,
473
+ async execute(args, exec) {
474
+ const { record } = await reader.read(exec);
475
+ return {
476
+ pack: args.pack,
477
+ problems: checkWorldPack(record.directory, args.pack)
478
+ };
479
+ }
480
+ }),
481
+ defineTool({
482
+ name: "delete_world_pack_file",
483
+ description: "Remove a file of a pack of this world; it is moved into the world's .trash directory. Requires user approval.",
484
+ parameters: {
485
+ pack: packParameter,
486
+ path: pathParameter
487
+ },
488
+ output: jsonOutput$2,
489
+ async execute(args, exec) {
490
+ const { record } = await reader.read(exec);
491
+ const { trashPath, problems } = await deleteWorldPackFile(record.directory, args.pack, args.path);
492
+ return {
493
+ action: "deleted",
494
+ pack: args.pack,
495
+ path: args.path,
496
+ trashPath,
497
+ problems
498
+ };
499
+ }
500
+ })
501
+ ];
502
+ }
503
+ //#endregion
209
504
  //#region src/host/authoring/prompt-tools.ts
210
505
  const PROMPT_MUTATION_TOOLS = ["write_world_prompt", "delete_world_prompt"];
211
506
  const output$2 = (value) => [{
@@ -327,7 +622,10 @@ const AUTHORING_MUTATION_TOOLS = /* @__PURE__ */ new Set([
327
622
  "delete_world_element",
328
623
  "edit_world_relationship",
329
624
  "replace_world_plots",
330
- ...PROMPT_MUTATION_TOOLS
625
+ "write_world_trigger",
626
+ "delete_world_trigger",
627
+ ...PROMPT_MUTATION_TOOLS,
628
+ ...PACK_MUTATION_TOOLS
331
629
  ]);
332
630
  function result(action, kind, key, state, extra = {}) {
333
631
  return {
@@ -458,6 +756,43 @@ function authoredWorldWriteTools(reader) {
458
756
  };
459
757
  return result("replaced", "plots", "*", await editWorldPlots(world, { plots: args.plots.map(plotDocument) }));
460
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
+ }
461
796
  })
462
797
  ];
463
798
  }
@@ -469,12 +804,29 @@ async function authoringApproval(exec, next, reviewing = () => Promise.resolve(f
469
804
  if (!AUTHORING_MUTATION_TOOLS.has(exec.name) || exec.agent === void 0 || authoredWorldOf(exec.agent.session.id) === void 0) return await next();
470
805
  const args = exec.arguments;
471
806
  const prompt = PROMPT_MUTATION_TOOLS.includes(exec.name);
807
+ const pack = PACK_MUTATION_TOOLS.includes(exec.name);
472
808
  const importing = await reviewing(exec.agent.session.id);
809
+ if (importing && pack) return {
810
+ kind: "deny",
811
+ reason: "an import does not write interface packs; they are left to the person"
812
+ };
473
813
  if (importing && prompt && !PROSE_PROMPTS.includes(String(args["id"]))) return {
474
814
  kind: "deny",
475
815
  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`
476
816
  };
477
817
  if (importing) return await next();
818
+ if (pack) {
819
+ const target = `file “${String(args["path"])}” of interface pack “${String(args["pack"])}”`;
820
+ const remove = exec.name.startsWith("delete");
821
+ return {
822
+ kind: "ask",
823
+ reason: `${remove ? "delete" : "write"} authored world ${target}`,
824
+ displayReason: {
825
+ en: `${remove ? "Delete" : "Write"} ${target} in the world files?`,
826
+ zh: `${remove ? "删除" : "写入"}世界文件中界面包“${String(args["pack"])}”的文件“${String(args["path"])}”?`
827
+ }
828
+ };
829
+ }
478
830
  if (prompt) {
479
831
  const target = `prompt “${String(args["language"])}/${String(args["id"])}”`;
480
832
  const remove = exec.name.startsWith("delete");
@@ -487,20 +839,111 @@ async function authoringApproval(exec, next, reviewing = () => Promise.resolve(f
487
839
  }
488
840
  };
489
841
  }
490
- 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";
491
843
  const key = typeof args["key"] === "string" ? args["key"] : "";
492
844
  const target = key === "" ? kind : `${kind} “${key}”`;
493
- 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";
494
846
  return {
495
847
  kind: "ask",
496
848
  reason: `${action.toLowerCase()} authored world ${target}`,
497
849
  displayReason: {
498
850
  en: `${action} ${target} in the world files?`,
499
- zh: `${action === "Create" ? "创建" : action === "Delete" ? "删除" : "编辑"}世界文件中的${target}?`
851
+ zh: `${action === "Create" ? "创建" : action === "Delete" ? "删除" : action === "Write" ? "写入" : "编辑"}世界文件中的${target}?`
500
852
  }
501
853
  };
502
854
  }
503
855
  //#endregion
856
+ //#region src/host/authoring/pack-jail.ts
857
+ /** DSH's own file tools, which the world authoring chat uses on the interface packs and nothing else. */
858
+ const PACK_FILE_TOOLS = [
859
+ "read",
860
+ "write",
861
+ "edit"
862
+ ];
863
+ const WRITING = ["write", "edit"];
864
+ /** The most text a call may carry. */
865
+ const MAX_PACK_TEXT = 204800;
866
+ function unsafePath(ui, path) {
867
+ const parts = relative(ui, path).split(sep);
868
+ let current = ui;
869
+ for (const part of ["", ...parts]) {
870
+ if (part !== "") current = join(current, part);
871
+ try {
872
+ if (lstatSync(current).isSymbolicLink()) return `the path passes through the symbolic link ${current}`;
873
+ } catch (error) {
874
+ if (error.code === "ENOENT") break;
875
+ if (error.code === "ENOTDIR") return `${current} cannot be traversed as a folder`;
876
+ throw error;
877
+ }
878
+ }
879
+ }
880
+ /**
881
+ * Why a call of a file tool is not one on an interface pack of the world, or nothing when it is: the file must be a text
882
+ * file of a pack folder `<world>/ui/<pack>/`, and a write must not carry more text than a pack file may hold.
883
+ * @param path - the absolute path asked for.
884
+ * @param world - the world's folder.
885
+ */
886
+ function packFileProblem(tool, path, world, texts = []) {
887
+ const ui = join(world, "ui");
888
+ const inside = relative(ui, path);
889
+ const segments = inside.split(sep);
890
+ const hint = `in this chat the file tools reach only the text files of the world's interface packs, ${join(ui, "<pack>", "<file>")}. Nothing, not another path and not sandbox_permissions, lifts that: do not try again for this file, tell the person that it cannot be changed from here`;
891
+ if (inside === "" || inside.startsWith("..") || isAbsolute(inside) || segments.length < 2) return `${path} is not a file of an interface pack: ${hint}`;
892
+ if (!isPackId(segments[0])) return `"${segments[0]}" is not a usable pack name (letters, digits, "-" and "_"): ${hint}`;
893
+ if (segments.some((segment) => segment.startsWith("."))) return `${path}: names may not start with a dot`;
894
+ if (!TEXT_EXTENSIONS.includes(extname(path).slice(1).toLowerCase())) return `${path} is not a text file of a pack (${TEXT_EXTENSIONS.join(", ")}); pictures and other files are added by hand`;
895
+ const unsafe = unsafePath(ui, path);
896
+ if (unsafe !== void 0) return `${path}: ${unsafe}; file tools do not follow symbolic links in interface packs`;
897
+ if (WRITING.includes(tool) && texts.some((text) => Buffer.byteLength(text) > 204800)) return `a call may carry at most ${MAX_PACK_TEXT / 1024} KB of text`;
898
+ }
899
+ const textOf = (value) => typeof value === "string" ? [value] : [];
900
+ /**
901
+ * Keeps DSH's `read`, `write` and `edit` on the interface packs of the world in an authoring chat, and asks the person before
902
+ * any change. It stands first in the chain, so that what it refuses cannot be let through by a listener after it; and what a
903
+ * later listener decides still stands: a plugin that denies or asks keeps doing so, and only a plain allow becomes an ask.
904
+ */
905
+ async function packJail(exec, next, deps) {
906
+ const chat = exec.agent?.session.id;
907
+ if (!PACK_FILE_TOOLS.includes(exec.name) || chat === void 0 || authoredWorldOf(chat) === void 0) return await next();
908
+ const world = await deps.worldDirectory(chat);
909
+ if (world === void 0) return {
910
+ kind: "deny",
911
+ reason: "the world of this chat no longer exists"
912
+ };
913
+ const args = exec.arguments;
914
+ const requested = args["file_path"];
915
+ if (typeof requested !== "string" || requested === "" || requested.startsWith("~")) return {
916
+ kind: "deny",
917
+ reason: "file_path must be a path of an interface pack of this world"
918
+ };
919
+ const path = resolve(exec.agent?.session.header.cwd ?? world, requested);
920
+ const problem = packFileProblem(exec.name, path, world, [...textOf(args["content"]), ...textOf(args["new_string"])]);
921
+ if (problem !== void 0) return {
922
+ kind: "deny",
923
+ reason: problem
924
+ };
925
+ const writing = WRITING.includes(exec.name);
926
+ if (writing && await deps.reviewing(chat)) return {
927
+ kind: "deny",
928
+ reason: "an import does not write interface packs; they are left to the person"
929
+ };
930
+ const decision = await next();
931
+ if (!writing || decision.kind !== "allow") return decision;
932
+ const target = `“${relative(join(world, "ui"), path)}”`;
933
+ return {
934
+ kind: "ask",
935
+ reason: `${exec.name} interface pack file ${target}`,
936
+ displayReason: {
937
+ en: `${exec.name === "write" ? "Write" : "Edit"} ${target} of an interface pack in the world files?`,
938
+ zh: `${exec.name === "write" ? "写入" : "编辑"}世界文件中界面包的文件${target}?`
939
+ }
940
+ };
941
+ }
942
+ /** Puts the jail first in the chain of `tools/pre-execute`: what it refuses cannot be let through by a listener after it. */
943
+ function registerPackJail(ctx, deps) {
944
+ ctx.on("tools/pre-execute", (exec, next) => packJail(exec, next, deps), { prepend: true });
945
+ }
946
+ //#endregion
504
947
  //#region src/host/import/tools.ts
505
948
  const SURVEY_TOOL = "import_survey";
506
949
  const BUILD_TOOL = "import_build";
@@ -729,6 +1172,7 @@ function apply(ctx) {
729
1172
  for (const tool of authoredWorldReadTools(reader)) ctx.tools.register(tool);
730
1173
  for (const tool of authoredWorldWriteTools(reader)) ctx.tools.register(tool);
731
1174
  for (const tool of worldPromptTools(reader)) ctx.tools.register(tool);
1175
+ for (const tool of worldPackTools(reader)) ctx.tools.register(tool);
732
1176
  for (const tool of importTools(ctx.roleplayWorlds, () => ctx.roleplayImport.settings, prompting)) ctx.tools.register(tool);
733
1177
  importHooks(ctx, ctx.roleplayWorlds, prompting);
734
1178
  const reviewing = async (chat) => {
@@ -736,6 +1180,14 @@ function apply(ctx) {
736
1180
  const record = id === void 0 ? void 0 : await ctx.roleplayWorlds.find(id);
737
1181
  return record !== void 0 && await isReviewing(record.directory);
738
1182
  };
1183
+ const worldDirectory = async (chat) => {
1184
+ const id = authoredWorldOf(chat);
1185
+ return id === void 0 ? void 0 : (await ctx.roleplayWorlds.find(id))?.directory;
1186
+ };
1187
+ registerPackJail(ctx, {
1188
+ worldDirectory,
1189
+ reviewing
1190
+ });
739
1191
  ctx.on("tools/pre-execute", (exec, next) => authoringApproval(exec, next, reviewing));
740
1192
  for (const [name, order, id] of [[
741
1193
  "WORLD_AUTHORING_PERSONA",